AngularJS Factory and Observer Pattern
HTML
<div ng-app="app" ng-controller="testController">
<div ng-repeat="notification in notifications">{{notification}}</div>
</div>
JavaScript
angular.module('app', [])
.factory('TestService', function () {
var _subscribers = [];
setInterval(function () {
// every 1 second, notify all subscribers
console.log(_subscribers);
angular.forEach(_subscribers, function (cb) {
cb('tester special @ ' + new Date());
});
}, 5500);
return {
subscribe: function (cb) {
_subscribers.push(cb);
}
};
})
.controller('testController', function ($scope, TestService) {
$scope.notifications = ['nothing yet'];
TestService.subscribe(function (notification) {
$scope.$apply(function () {
$scope.notifications.push('got ' + notification);
});
});
});