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.

Revisions

  1. damnit created this gist Nov 30, 2015.
    42 changes: 42 additions & 0 deletions ng_observe.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    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();