AngularJS Broadcast Event
by anazimok
HTML
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<input type="text" ng-model="message">
<button ng-click="handleClick()">Broadcast</button>
</div>
<div ng-controller="SecondController">
<div> {{ message }} </div>
</div>
</div>
CSS
</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ --> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script> <style> .ng-invalid {
border: 1px solid red;
}
JavaScript
// declare a module
var app = angular.module('myApp', []);
app.factory('sharedService', function($rootScope) {
return {
broadcast: function(msg) {
$rootScope.$broadcast('messageUpdate', msg);
}
};
});
app.controller('MyCtrl', function ($scope, sharedService) {
$scope.handleClick = function() {
sharedService.broadcast($scope.message);
}
});
app.controller('SecondController', function($scope, sharedService) {
//$scope.message = 'Default';
$scope.$on('messageUpdate', function(event, message) {
//$scope.updateMessage(message);
$scope.message = message;
});
});