Skip to content

Instantly share code, notes, and snippets.

@damnit
Created November 30, 2015 15:38
Show Gist options
  • Save damnit/f0401b38e7f67455fbc2 to your computer and use it in GitHub Desktop.
Save damnit/f0401b38e7f67455fbc2 to your computer and use it in GitHub Desktop.
var app = angular.module('damnit.example.observer', ['ngRoute']);
app.config(function($locationProvider, $routeProvider) {
$locationProvider.html5Mode(true).hashPrefix('!');
$routeProvider
.when('/', {
controller: 'FooController as ctrl',
template: '<h1 ng-controller="BarController as bctrl">this is <a ng-click="bctrl.publish(\'bar\')">foo</a></h1>'
})
.otherwise('/');
});
app.service('regService', [function(){
var observers = [];
return {
'register': function(scope) {
observers.push(scope);
},
'broadcast': function(data) {
var i;
for(i=0; i<observers.length; i++) {
observers[i].notify(data);
}
}
};
}]);
app.controller('FooController', ['regService', function(regService) {
this.notify = function (data) {
console.log('FooController#notify');
console.log(data);
};
regService.register(this);
}]);
app.controller('BarController', ['regService', function(regService) {
this.publish = function (data) { regService.broadcast(data); };
this.notify = function (data) {
console.log('BarController#notify');
console.log(data);
};
}]);
app.run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment