解析AngularJS service vs factory

时间:2015-04-03 23:48:38   收藏:0   阅读:400

原文来自: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 }

 

 

原文:http://www.cnblogs.com/xc145214/p/4391136.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!