Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html>
- <head>
- <title>Angular Observer Pattern</title>
- </head>
- <body>
- <div ng-app="app">
- <ul ng-controller="myController as vm">
- <li ng-repeat="notification in vm.notifications">{{notification}}</li>
- </ul>
- </div>
- <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
- <script>
- angular.module('app', []);
- angular.module('app').factory('Observer', Observer);
- function Observer() {
- var _subscribers = [];
- setInterval(function () {
- console.log(_subscribers);
- angular.forEach(_subscribers, function (cb) {
- cb('something special @ ' + new Date());
- });
- }, 2500);
- function subscribe(cb) {
- _subscribers.push(cb);
- }
- return {
- subscribe: subscribe
- };
- }
- angular.module('app').controller('myController', myController);
- function myController($scope, Observer) {
- var vm = this;
- var _stopWatchingSignIn = Observer.subscribe(notify);
- vm.notifications = ['nothing yet'];
- function notify(notification) {
- $scope.$apply(function () {
- vm.notifications.push('got ' + notification);
- });
- }
- $scope.$on('$destroy', function (){
- _stopWatchingSignIn();
- });
- }
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement