Services都是单例的,就是说在一个应用中,每一个Serice对象只会被实例化一次(用$injector服务),主要负责提供一个接口把特定函数需要的方法放在一起。
最常见的创建方法就是用angular.module API 的factory模式:
angular.module('myApp.services', [])
.factory('githubService', function() {
var serviceInstance = {};
// 我们的第一个服务
return serviceInstance;
});
这个服务并没有做实际的事情,但是他向我们展示了如何去定义一个service。创建一个service就是简单的返回一个函数,这个函数返回一个对象。这个对象是在创建应用实例的时候创建的(记住,这个对象是单例对象)。
下面创建一个service 用于读取数据:
1、首先 定义一个服务:
var app = angular.module('myapp', []);
//定义一个服务
app.factory('myservice',['$http',function($http){
return{
querydata:function(){
return $http({
method: 'GET',
url: 'js/data.json'
});
}
};
}]);
2、调用这个服务
//调用服务
app.controller('ServiceController',['$scope','myservice','$http',function($scope,myservice,$http){
myservice.querydata().success(function(data,status){
$scope.infos=data;
});
}]);
index.html 页面:
<div ng-controller="ServiceController">
<ul>
<li ng-repeat="phone in infos">
<span>{{phone.title}} + {{phone.url}}</span>
</li>
</ul>
</div>