标签:
昨晚项目组做了angular分享,刚好有讨论到这个问题。虽然许久不做前端开发,但是兴趣所致。就查阅了下资料,以便后续需要使用
自己的理解:service是new出来的,factory是直接使用就能获得到service对象,service多了一个this。provider可以初始化注入之前进行一些全局配置,还有就是需要通过$get方法来获得
比较简单的一个理解
app.factory(‘a‘, fn);
app.service(‘b‘, fn);
app.provider(‘c‘, fn);
The difference between the three is that:
a‘s stored value comes from running fn.b’s stored value comes from newing fn.c’s stored value comes from first getting an instance by newing fn, and then running a $getmethod of the instance.Which means there’s something like a cache object inside AngularJS, whose value of each injection is only assigned once, when they‘ve been injected the first time, and where:
cache.a = fn() cache.b = new fn() cache.c = (new fn()).$get()
一篇关于三者区别的英文资料 :http://tylermcginnis.com/angularjs-factory-vs-service-vs-provider/
看不来的可以看下中文翻译:http://www.oschina.net/translate/angularjs-factory-vs-service-vs-provider
但是不推荐,还是老老实实看英文为好
最后来篇比较长的
var myApp = angular.module(‘myApp‘, []);
//Service style, probably the simplest one
myApp.service(‘helloWorldFromService‘, function() {
this.sayHello = function() {
return "Hello, World!"
};
});
//Factory style, more involved but more sophisticated
myApp.factory(‘helloWorldFromFactory‘, function() {
return {
sayHello: function() {
return "Hello, World!"
}
};
});
//Provider style, full blown, configurable version
myApp.provider(‘helloWorld‘, function() {
// In the provider function, you cannot inject any
// service or factory. This can only be done at the
// "$get" method.
this.name = ‘Default‘;
this.$get = function() {
var name = this.name;
return {
sayHello: function() {
return "Hello, " + name + "!"
}
}
};
this.setName = function(name) {
this.name = name;
};
});
//Hey, we can configure a provider!
myApp.config(function(helloWorldProvider){
helloWorldProvider.setName(‘World‘);
});
function MyCtrl($scope, helloWorld, helloWorldFromFactory, helloWorldFromService) {
$scope.hellos = [
helloWorld.sayHello(),
helloWorldFromFactory.sayHello(),
helloWorldFromService.sayHello()];
}
同事的总结资料:


angular之service、factory预provider区别
标签:
原文地址:http://www.cnblogs.com/draem0507/p/4817388.html