javascript - 使用工厂内部路由 Controller

标签 javascript ajax angularjs

我有这样的工厂:

angular.module('commentsApp')
        .factory("getCommentsFactory", getCommentsFactory);

function getCommentsFactory(scope, $http)
{
    return {
        getComments: getComments
    };

    function getComments()
    {
        return $http.get("/api/comments/" + scope.param)
                .then(getCommentsComplete)
                .catch(getCommentsFailed);

        function getCommentsComplete(data) {
        //GET ALL USER AND COMMENTS TOGETHER
            return data;
        }

        function getCommentsFailed(error) {
            scope.setLoading(false);
            return error;
        }
    }

}

当我尝试从我的 Controller 调用这个工厂时,如下所示:

.controller('CommentsCtrl',function($scope,$http,$routeParams,getCommentsFactory){
              $scope.param = $routeParams.id;
              $scope.comments = [];
              getCommentsFactory.getComments()
                      .then(function(data){
                          console.log(data);
              });
...

我收到错误:

Error: [$injector:unpr] http://errors.angularjs.org/1.4.3/$injector/unpr?p0=scopeProvider%20%3C-cope%20%3C-%20getCommentsFactory at Error (native) at https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:6:416 at https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:40:375 at Object.d [as get] (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:38:364) at https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:40:449 at d (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:38:364) at Object.e [as invoke] (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:39:124) at Object.$get (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:37:98) at Object.e [as invoke] (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:39:156) at https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:40:478

有人知道问题出在哪里吗?

最佳答案

问题是您正在工厂中注入(inject)称为“范围”的东西,但没有可以在那里注入(inject)的范围。

如果您需要来自 Controller 的值,您应该将其作为函数中的参数传递。您无法在工厂中注入(inject) Controller 作用域。

关于javascript - 使用工厂内部路由 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32661034/

相关文章:

javascript - 通过单个 Ajax 调用向 Spring Boot 提交多个表单

javascript - AngularJs 格式化极小的十进制数 (1e-8)

css - Chrome 中导航栏的错误(UI-Bootstrap)

javascript - Angular 7 迭代表

javascript - 我可以使用带有两个变量的 case/switch 语句吗?

javascript - Angular 使用静态文件加载器翻译默认语言

jquery - 通过 jQuery 提交后显示 Django 表单的验证错误 `.ajax`

javascript - 从动态选择框获取值

javascript - AngularJS $rootScope.$on 在迁移到 Angular2 的上下文中的替代方案

javascript - 在同一 Fetch POST API 调用中返回 JSON