http://www.cooklife.cn/detail/54c36a3ac93620284e964b57#View
angular的控制器同view绑定,当view不需要的时候控制器就会被销毁,因此控制器的作用域是同其绑定的视图一致的。
服务提供了一种在整个应用的生命周期内保存数据的方法,可以通过服务在控制器间进行通信。
注册服务
angular应用中提供了五种方法来创建服务
factory()
angular.module("test").factory('testService', ['$http', function($http){ return { funcName : function(){ } } }])
factory接受两个参数
name(字符串):注册的服务名
getfn(函数):angular创建服务实例的时候被调用,服务是单例,因此生命周期内只会被调用一次。
service()
var testConstructor = function($http){ this.mehtodName = function(){ } } angular.service('testService', testConstructor);
service()可以注册一个支持构造函数的服务,方法接受两个参数
name(字符串):注册的服务名
constructor(函数):构造函数,在创建服务实例的时候通过new关键字去实例化服务对象
constant()
angular.module('test').constant('apiKey', 'value'); angular.module('test').controller('testController', function(apiKey){ })接受两个参数,注册的常量名以及值
可以将一个已经存在的变量值注册为服务,并注入到应用的其他部分中。
value()
同constant()一样,将常量发布为服务,所不同的是,constant()所定义的常量在config配置函数中可以访问得到,value()定义的值在config配置函数中访问不到。
provider()
angular.module('test').provider('testService', { $get : function(){ } })
provider()方法接受两个参数,一个字符串作为注册的服务名称,另外一个是具有$get()方法的对象,$injector在 实例化服务的时候会通过$get创建服务实例。
何时使用factory(),何时使用provider()?
如果在多个应用中使用同一个服务的时候,需要针对不同的应用对于服务做一些配置,那么我们就应该使用provider()
angular.module('myApp', []).provider('githubService', function($http) { // 默认的,私有状态 var githubUrl = 'https://github.com' setGithubUrl: function(url) { // 通过.config改变默认属性 if (url) { githubUrl = url } }, method: JSONP, // 如果需要,可以重写 $get: function($http) { self = this; return $http({ method: self.method, url: githubUrl + '/events'}); } }); angular.module('myApp', []).config(function(githubServiceProvider) { githubServiceProvider.setGithubUrl("git@github.com"); });上面的例子中我们针对应用myApp,在config配置函数中设置了url,对于不同的应用,同一个服务我们可以在这里做不同的配置,而不必修改服务的源码。
对服务进行装饰
有些时候,使用angular内置的服务,或者使用第三方封装好的服务,我们想给服务加一些附加的功能,但是又不想修改服务的源码,那么肿么办呢?
我们可以使用$provide.decorator()来对服务进行加强。
decorator()接受两个参数:
name():需要装饰的服务名称
decoratorFn(fn):函数,我们可以通过$delegate把需要加强的服务注入到该函数内,在decoratorFn中对于原有的服务做一些扩展。