码迷,mamicode.com
首页 > Web开发 > 详细

解析AngularJS service vs factory

时间:2015-04-03 23:51:44      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:

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

 

 

解析AngularJS service vs factory

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!