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()];
}?
The value, factory, service, constant, and provider methods are all providers. They teach the Injector how to instantiate the Services.
1.the Value Recipe is the simplest case, where you instantiate the Service yourself and provide theinstantiated value to the injector.
2.The Factory recipe gives the Injector a factory function that it calls when it needs to instantiate the service. When called, the factory function creates and returns the service instance. The dependencies of the Service are injected as the functions‘s arguments. So using this recipe adds the following abilities:The Service recipe is almost the same as the Factory recipe, but here the Injector invokes aconstructor with the new operator instead of a factory function.
ability to use other services (have dependencies)
service initialization
delayed/lazy initialization
3.The Provider recipe is usually overkill. It adds one more layer of indirection by allowing you to configure the creation of the factory.
You should use the Provider recipe only when you want to expose an API for application-wide configuration that must be made before the application starts. This is usually interesting only for reusable services whose behavior might need to vary slightly between applications.
4.The Constant recipe is just like the Value recipe except it allows you to define services that are available in the config phase. Sooner than services created using the Value recipe. Unlike Values, they cannot be decorated using decorator.
relative information on stackoverflow: http://stackoverflow.com/questions/15666048/angular-js-service-vs-provider-vs-factory
【备忘录】provider, factory, service, hello world example,布布扣,bubuko.com
【备忘录】provider, factory, service, hello world example
原文:http://www.cnblogs.com/xiaoroad/p/3812091.html