Blog- AngularJS-Simple-service

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>     
        <a ng-click="syncDataWithService()">syncDataWithService</a><br>           
    </div>
    <hr/>
    <div ng-controller="ControllerB">
        ControllerB.X = {{x}}<br/>
        <a ng-click="incrementDataInService()">incrementDataInService</a><br>     
        <a ng-click="syncDataWithService()">syncDataWithService</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 () {
        var x=5 ;
        return {
            increase : function() {
                x++;
            },
            getX : function() {
                return x;
            }
       };
    })

function ControllerA($scope, myService) {
    $scope.x = 1;
    $scope.incrementDataInService= function() {
        myService.increase();
    }
    $scope.syncDataWithService= function() {
        $scope.x = myService.getX();
    }        
}
    
function ControllerB($scope, myService) {
   $scope.x = 1;
    $scope.incrementDataInService= function() {
        myService.increase();            
    }
    $scope.syncDataWithService= function() {
        $scope.x = myService.getX();
    }    
}