我有几个函数在不同的 Controller 中使用,与其将其多次复制并粘贴到 Controller 中,不如将其拉出并放置在工厂中。
但是,当我尝试通过 Angular {{expressions}}
调用 HTML 中的函数时,它不起作用。
相反,我在每个 Controller 的 $scope 中创建了调用工厂函数的函数,以便 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 中调用函数了吗?谢谢。
最佳答案
添加 $scope.MakeGraph = MakeGraph
到你的 Controller
controllers.controller('MyController', ['$scope', 'MakeGraph', '$routeParams', function($scope, MakeGraph, $routeParams){
$scope.whichItem = $routeParams.itemId;
$scope.MakeGraph = MakeGraph
}])
然后您可以从您的 View 访问MakeGraph
例子:
<a ng-click="MakeGraph.getVotes(12)"> Click me </a>
请注意,如果您在服务中返回 promise ,您可能仍需要将 then 包装在您的 Controller 中,以便正确处理 .success/.then/.error ...
事件
关于javascript - 工厂函数的依赖注入(inject)(AngularJS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24453699/