繁体   English   中英

使用工厂的依赖注入函数(AngularJS)

[英]Dependency Injection of functions with Factories (AngularJS)

我有一些在不同控制器中使用的功能,而不是多次复制和粘贴到控制器中,我想把它拉出来放在工厂里。

但是,当我尝试通过Angular {{expressions}}调用HTML中的函数时,它不起作用。

相反,我在调用工厂函数的每个控制器的$ 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添加到您的控制器

controllers.controller('MyController', ['$scope', 'MakeGraph', '$routeParams', function($scope, MakeGraph, $routeParams){
    $scope.whichItem = $routeParams.itemId;
    $scope.MakeGraph = MakeGraph
}])

然后你可以从你的视图访问MakeGraph

例:

<a ng-click="MakeGraph.getVotes(12)"> Click me </a>

请注意,如果您在服务中返回promises,您可能仍需要在控制器中进行换行以正确处理.success / .then / .error ...事件

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM