var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
});
app.factory('myService', function() {
var myService = {
callbacks: [],
registerCallback: _registerCallback,
notifyObservers: _notifyObservers
};
//register an callback (observer)
function _registerCallback (callback){
myService.callbacks.push(callback);
}
//call this when your data change and you want to 'alert' everyOne
function _notifyObservers(data){
myService.callbacks.forEach(function(callback){
callback(data);
});
}
return myService;
});
app.controller('Controller1', function(myService) {
var vm1 = this;
vm1.text = '';
//Register the function as callback
myService.registerCallback(alertCallback);
function alertCallback(data){
vm1.text = data;
}
});
app.controller('Controller2', function($scope, myService) {
var vm2 = this;
vm2.postMessage = function() {
myService.notifyObservers(vm2.text);
vm2.text = '';
};
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.8/angular.js" data-semver="1.4.8"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-controller="Controller1 as vm1">
<h1>Controller 1</h1>
<p>
Controller 1 Message: <span data-ng-bind="vm1.text"></span>
</p>
</div>
<p></p>
<div ng-controller="Controller2 as vm2">
<h1>Controller 2</h1>
<p>
Controller 2 Message: <input type="text" ng-model="vm2.text">
<button ng-click="vm2.postMessage()">Notify</button>
</p>
</div>
</body>
</html>
/* Put your css in here */
This example demonstrate the usage of Angular.Js service as a messenger (notifier) between controllers.
This is a good example of using the stateless Service to pass data/notify different controllers of a change that happen.
Be aware not to overuse this functionality (complex callbacks, or too many callbacks) - if this is the case, choose a different approach
How does it work:
1. Service holds a callbacks collection
2. Service has a method to add/register a new callback
3. Service has a notify method , that if called will invoke every callback
4. Controllers need to register a callback to service
5. Controllers need to call service notify method to alert of a change