さまざまなコントローラーで使用されている関数がいくつかありますが、それをコントローラーに何度もコピーして貼り付けるのではなく、引き出して工場に配置したいと考えています。
ただし、Angular を介して HTML で関数を呼び出そうとすると、機能し{{expressions}}
ません。
代わりに、ファクトリの関数を呼び出す各コントローラーの $scopes 内に関数を作成して、DOM が式を読み取れるようにしましたが、これは冗長に思えます。これを修正して、ファクトリから関数を簡単に呼び出せるようにする方法はありますか?
これが私が最初に試したものです:
index.html :
<div ng-controller="MyController">
The rating of this item is: {{MakeGraph.getRating(whichItem)}}<br />
The votes of this item is: {{MakeGraph.getVotes(whichItem)}}
</div>
MyController.js :
controllers.controller('MyController', ['$scope', 'MakeGraph', '$routeParams', function($scope, MakeGraph, $routeParams){
$scope.whichItem = $routeParams.itemId;
//no other reference to MakeGraph here
}])
factory.js :
app.factory('MakeGraph', function(){
var service = {};
service.getRating = function(itemNo){
...
return ...;
};
service.getVotes = function(itemNo){
...
return ...;
};
return service;
});
代わりに、 MyController を次のように変更した場合にのみ機能させることができます。
$scope.getRating = function(){
return MakeGraph.getRating(itemNo);
};
$scope 内で関数を呼び出す必要がないように、これを修正できますか? ありがとう。