解析AngularJS service vs factory

原文来自:http://blog.manishchhabra.com/2013/09/angularjs-service-vs-factory-with-example/

What is an AngularJS service or factory?

Singleton.

Yes! That one word is enough to define AngularJS services. The purpose of AngularJS service / factory function is to generate a single object or function that represents the service to rest of the application. That object or function is passed as a parameter to any other factory function which specifies a dependency on this service.

Services

Syntaxmodule.service(‘serviceName‘, function);

Result: When declaring serviceName as an injectable argument you will be provided with the instance of a function passed to module.service.

Usage: Could be useful for sharing utility functions that are useful to invoke by simply appending () to the injected function reference. Could also be run with injectedArg.call(this) or similar.

Example:

 1 varapp = angular.module(‘myApp‘, []);
 2      
 3 // Service definition
 4 app.service(‘testService‘, function(){
 5     this.sayHello= function(text){
 6         return"Service says \"Hello "+ text + "\"";
 7     };       
 8 });
 9  
10 // AngularJS Controller that uses the service
11 functionHelloCtrl($scope, testService)
12 {
13     $scope.fromService = testService.sayHello("World");
14 }

Factories

Syntaxmodule.factory(‘factoryName‘, function);

Result: When declaring factoryName as an injectable argument you will be provided the value that is returned by invoking the function reference passed to module.factory.

Usage: Could be useful for returning a ‘class’ function that can then be new’ed to create instances.

 1 varapp = angular.module(‘myApp‘, []);
 2  
 3 // Factory
 4 app.factory(‘testFactory‘, function(){
 5     return{
 6         sayHello: function(text){
 7             return"Factory says \"Hello "+ text + "\"";
 8         } 
 9     }              
10 });
11  
12 // AngularJS Controller that uses the factory
13 functionHelloCtrl($scope, testFactory)
14 {
15     $scope.fromFactory = testFactory.sayHello("World");
16 }

 

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。