angularjs service example

by fabregat

HTML

<div ng-app="MyApp">
    <div ng-controller="MyCtrl">
        dataService1 = {{data1}} 
        <br />
        dataService2 country = {{data2a}}
        <br />
        dataService2 state = {{data2b}}
        <br />
        dataService2 capital = {{data2c}}
        <br />
        dataService3 = {{data3}}
    </div>
</div>

JavaScript

var app = angular.module('MyApp', [])

app.service('Service1', function(){
    return {
        ajxResponse1: 'dataFromService1'
    };
});
app.service('Service2', function(){
    return {
        ajxResponse2: {"country": {
            "name": "US",
	"states":[
		{"name": "Alabama", 
		 "capital": "Montgomery"
		},
		{"name": "New York", 
		 "capital": "Albany"
		}
            ]
                                }
                      }
    }});
app.service('Service3', function(){
    return {
        ajxResponse3: 'dataFromService3'
    };
});


function MyCtrl($scope, Service1, Service2, Service3){
    alert('Entering MyCtrl');
    $scope.data1 = Service1.ajxResponse1;
    $scope.data2a = Service2.ajxResponse2.country.name;
    $scope.data2b = Service2.ajxResponse2.country.states[1].name;
    $scope.data2c = Service2.ajxResponse2.country.states[1].capital;
    $scope.data3 = Service3.ajxResponse3;
    alert('Exiting MyCtrl');
}