[フレーム]
Last Updated: February 25, 2016
·
11.22K
· phantom

Angularjs - service vs factory vs provider

Angularjs – service vs factory vs provider

There is a main diference:

var module = angular.module('mymodule');
module.service('a', function(){
 this.data = [];
 this.add = function(){};
 this.remove = function(){};
});
module.factory('b', function(){
 function c(p){
 this.data = [];
 this.p = p;
 }

 c.prototype = {
 add : function(){},
 remove : function(){}
 }

 return c;
});
module.factory('c', function(){ 
 this.$get = function(){

 }
});

a - is constructor

new a(); 

b - is function

b();

c - angular create an instance of function than calls this.$get function

new ProviderFunc().$get();

Factory:
Mostly used to create a new class instance on each controller, below example data property in bb object will not be shared from TestController -> Test2Controller because its new instance.

module.controller('TestController', function($scope, b){
 $scope.bb = new b('you can pass parameter');
});

module.controller('Test2Controller', function($scope, b){
 $scope.bb = new b('you can pass parameter');
});

Service:
Mostly used to share data over the application. Data array will be visible from TestController to Test2Controller

module.controller('TestController', function($scope, a){
 $scope.bb = a;
});

module.controller('Test2Controller', function($scope, a){
 $scope.bb = a;
});

Provider:
Provider can be configurabile on application instance.

module.config(function(c){
 c.add([
 {
 a:1
 }
 ])
});

AltStyle によって変換されたページ (->オリジナル) /