如何使用另一个模块中定义的服务而不是控制器调用它?

时间:2016-06-23 17:31:41

标签: angularjs

我有一个定义了服务的模块:

var ngError = angular.module('ngError', []);

ngError.service('ErrorService', ['$scope', function($scope) {
    $scope.displayErrors = function(errors) {
        alert(errors);
    }
}]);

然后我有另一个模块:

var ngLogin = angular.module('ngLogin', ['ngError']);

哪个控制器尝试使用ngError上定义的第一个服务:

ngLogin.controller('LoginCtrl', ['$scope', 'LoginService', 'ErrorService', function($scope, LoginService, ErrorService) {
    $scope.user = {};
    $scope.user.id = 0;
    $scope.user.token = '';

    $scope.login = function(callback) {
     LoginService.login($scope.user.username, $scope.user.password, function(token) {
        $scope.setToken(token);
        $scope.$apply();
        if (typeof callback === 'function') {
            callback(callback);
        }
     }, function(errors) {
        ErrorService.displayErrors(errors);
     });
};
}]);

但是有些原因造成了以下错误:

Unknown provider: $scopeProvider <- $scope <- ErrorService

2 个答案:

答案 0 :(得分:0)

您无法在服务中使用$scope。按如下方式更改服务,它将起作用:

var ngError = angular.module('ngError', []);

ngError.service('ErrorService', [function() {
    this.displayErrors = function(errors) {
        alert(errors);
    }
}]);

答案 1 :(得分:0)

尝试这样,最适合我

&#13;
&#13;
[
    {id: "1", name: "Snatch", type: "crime"},
    {id: "2", name: "Witches of Eastwick", type: "comedy"},
    {id: "3", name: "X-Men", type: "action"},
    {id: "4", name: "Ordinary People", type: "drama"},
    {id: "5", name: "Billy Elliot", type: "drama"},
    {id: "6", name: "Toy Story", type: "children"}
]
&#13;
&#13;
&#13;