Blog- AngularJS-Simple-service-with-broadcast

by beltiste

HTML

<script src="http://www.flocations.com/static/vendor/angularjs/1.0.2/angular.min.js"></script>
<div ng-app="myApp">
    <div ng-controller="ControllerA">
        ControllerA.X = {{x}}<br/>
        <a ng-click="incrementDataInService()">incrementDataInService</a><br>     
    </div>
    <hr/>
    <div ng-controller="ControllerB">
        ControllerB.X = {{x}}<br/>
        <a ng-click="incrementDataInService()">incrementDataInService</a><br>     
     </div>
</div>

CSS

</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ --> 
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<style>

JavaScript

angular.module('myApp', [])
    .service('myService',  function ($rootScope) {
        var x=5 ;
        return {
            increase : function() {
                x++;
                $rootScope.$broadcast('XChanged', x);
            }
       };
    })

function ControllerA($scope, myService) {
    $scope.x = 1;
    $scope.incrementDataInService= function() {
        myService.increase();
    }     
    $scope.$on('XChanged', function(event, x) {
        $scope.x = x;
    });        
}
    
function ControllerB($scope, myService) {
   $scope.x = 1;
    $scope.incrementDataInService= function() {
        myService.increase();            
    }
    $scope.$on('XChanged', function(event, x) {
        $scope.x = x;
    });           
}