据我了解,它们几乎都是一样的。主要区别在于它们的复杂性。提供者在运行时是可配置的,工厂更健壮一些,服务是最简单的形式。
看看这个问题AngularJS: Service vs provider vs factory
此外,这个要点可能有助于理解细微的差异。
来源:https ://groups.google.com/forum/#!topic/angular/hVrkvaHGOfc
jsFiddle:http: //jsfiddle.net/pkozlowski_opensource/PxdSP/14/
作者:帕维尔·科兹洛夫斯基
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()];
}