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

Dependency Injection of functions with Factories (AngularJS)

本文关键字:AngularJS 注入 依赖 函数 工厂      更新时间:2023-09-26

我有一些在不同控制器中使用的函数,而不是将其复制粘贴多次到控制器中,我想将其拉出来并将其放在工厂中。

然而,当我试图通过Angular {{expressions}}在HTML中调用该函数时,它不起作用。

相反,我在每个控制器的$作用域中创建了调用工厂函数的函数,以便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.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>

请注意,如果您在服务中返回承诺,您可能仍然需要将其包装在控制器中,以便正确处理.success / .then / .error ...事件