sevenLee
11/13/2015 - 8:10 AM

Angular : Notifying about changes from services to controllers

Angular : Notifying about changes from services to controllers

angular.module('app', []);

angular.module('app').controller('TheCtrl', function($scope, NotifyingService) {
    $scope.notifications = 0;
    
    $scope.notify = function() {
        NotifyingService.notify();
    };
    
    // ... stuff ...
    NotifyingService.subscribe($scope, function somethingChanged() {
        // Handle notification
        $scope.notifications++;
    });
});

angular.module('app').factory('NotifyingService', function($rootScope) {
    return {
        subscribe: function(scope, callback) {
            var handler = $rootScope.$on('notifying-service-event', callback);
            scope.$on('$destroy', handler);
        },

        notify: function() {
            $rootScope.$emit('notifying-service-event');
        }
    };
});
<div ng-controller=TheCtrl>
    <button ng-click=notify()>Notify</button>
    
    {{ notifications }}
</div>