AngularJS (16) factory 和 service
本篇範例程式碼(Plunker)
我們可以在控制器裡面寫函式,這一點你應該知道。你也許會發現當你有太多的成員函式時,會讓控制器程式碼變得太長。
app1.controller("myController", ['$scope', function($scope){
$scope.add = function(val1, val2){return val1+val2;};
$scope.sub = function(val1, val2){return val1-val2;};
$scope.int1 = $scope.add(10,20);
$scope.int2 = $scope.sub(50,30);
}]);
為了方便管理程式碼,AngularJS提供了factory()和service(),把函式包在一個「服務提供者(provider)」。
Factory
改寫上面的例子,我們宣告Maths為factory物件,負責提供add和sub這兩個函式。
myApp.factory("Maths", function(){
var fact = {};
fact.add = function(a, b) { return a + b; };
fact.sub = function(a, b) { return a - b; };
return fact;
});
或是可以批次定義
myApp.factory("Maths", function(){
return {
add: function(a, b) { return a + b ;}
sub: function(a, b) { return a - b; };
}
});
Service
我們也可以用service()
myApp.service("Maths", function(){
this.add = function(a, b) { return a + b; };
this.sub = function(a, b) { return a - b; };
});
完成!
你只需要匯入Maths,就可以讓控制器使用add和sub。
myApp.controller("myController", ['$scope', 'Maths',
function($scope, Maths){
$scope.int1 = Maths.add(10,20);
$scope.int2 = Maths.sub(20,20);
}]);
解釋一下,factory和service都是可以存放多個函式,只是service背後的流程是constructor injection,請看(providers官方說明)。
※ factory和service只可以給控制器用,不可以在HTML呼叫。
原因參考:Stackoverflow-How to call factory methods from HTML in angularjs?
HTML views can only be linked to Controller (using the $scope variable) or extended with Directives. Any other way is not an angular way :)
– Chandermani May 14 '13 at 14:28
所以,如果你還是想在HTML呼叫函式,就得跟本文開頭一樣,定義你的javascript函式嚕。
留言
張貼留言