Here is a good demonstration in Fiddle how to use a shared service in a directive and other controllers via $scope.$on
HTML
<div ng-controller="ControllerZero"> <input ng-model="message" > <button ng-click="handleClick(message);">BROADCAST</button> </div> <div ng-controller="ControllerOne"> <input ng-model="message" > </div> <div ng-controller="ControllerTwo"> <input ng-model="message" > </div> <my-component ng-model="message"></my-component>
Js
var myModule = angular.module('myModule', []); myModule.factory('mySharedService', function($rootScope) { var sharedService = {}; sharedService.message = ''; sharedService.prepForBroadcast = function(msg) { this.message = msg; this.broadcastItem(); }; sharedService.broadcastItem = function() { $rootScope.$broadcast('handleBroadcast'); }; return sharedService; });
In the same way, we can use the shared service in the directive. We can implement the controller section in the directive and use $scope.$on
myModule.directive('myComponent', function(mySharedService) { return { restrict: 'E', controller: function($scope, $attrs, mySharedService) { $scope.$on('handleBroadcast', function() { $scope.message = 'Directive: ' + mySharedService.message; }); }, replace: true, template: '<input>' }; });
And here are our three controllers where ControllerZero used as a trigger to call prepForBroadcast
function ControllerZero($scope, sharedService) { $scope.handleClick = function(msg) { sharedService.prepForBroadcast(msg); }; $scope.$on('handleBroadcast', function() { $scope.message = sharedService.message; }); } function ControllerOne($scope, sharedService) { $scope.$on('handleBroadcast', function() { $scope.message = 'ONE: ' + sharedService.message; }); } function ControllerTwo($scope, sharedService) { $scope.$on('handleBroadcast', function() { $scope.message = 'TWO: ' + sharedService.message; }); }
Cancel ControllerOne and ControllerTwo listening for message using the $scope.$on handler.
Maxim Shoustin Oct 19 '13 at 17:50 2013-10-19 17:50
source share