AngularJS服务未定义:未知提供者:$ scopeProvider< - $ scope

时间:2014-11-03 01:45:23

标签: javascript angularjs

我已经开始学习Angular JS了,我在向控制器中注入服务时遇到了问题。我正在尝试将ThreadFactory服务放入ThreadController,但是在调用时我收到了一个未定义的错误。任何建议都会很棒。我得到的错误是:

未知提供者:$ scopeProvider< - $ scope< - ThreadService

app.js

angular.module('threadsApp', ['ngRoute']);
angular.module('threadsApp')
    .config(function ($routeProvider, $locationProvider) {
        $routeProvider
            .when('/', {
                templateUrl: 'views/index.html',
            })
            .when('/selected/:topicName', {
                templateUrl: 'views/threads.html',
                controller: 'ThreadController',
            })
            .otherwise({
                redirectTo: "/"
            });
            $locationProvider.html5Mode(true);
    });

ThreadController.js

angular.module('threadsApp').controller("ThreadController",
    ["$scope", "$route", "$routeParams", "ThreadService", function ($scope, $route, $routeParams, ThreadService) {
    $scope.test = "Hello!";
    $scope.test2 = ThreadService.get();
}]);

ThreadService.js

angular.module('threadsApp').service("ThreadService", ["$scope", function ($scope) {
    return {
        get: function() {
            return "Hello";
        }
    }
}]);

进口顺序

    <script src="bower_components/jquery/dist/jquery.js"></script>
    <script src="bower_components/angular/angular.js"></script>
    <script src="bower_components/angular-route/angular-route.js"></script>
    <script src="bower_components/bootstrap/dist/js/bootstrap.js"></script>
    <script src="components/app.js"></script>
    <script src="components/bodyController.js"></script>
    <script src="components/TopicController.js"></script>
    <script src="components/ThreadService.js"></script>
    <script src="components/ThreadController.js"></script>

1 个答案:

答案 0 :(得分:21)

您实际上无法按照您尝试的方式$scope注入ThreadService。将它注入控制器时,$scope不是典型的服务。如果从 Threadservice.js 中删除$scope注入,我敢打赌错误会消失。

为了不冗余,可以在这里找到更全面的解释:

Injecting $scope into an angular service function()