2017-02-23 112 views
0

我正在处理一个角度项目,在那里我将新功能添加到较旧的项目。
我想用我的控制器注册一个服务,但得到一个错误,我的控制器无法找到服务中的功能。无法从控制器访问服务angularjs

这里是我的控制器是如何定义的(我知道这不是标准的方式,但我必须遵循这一点,因为整个应用程序一样。)

angular.module("test").controller("listCtrl", listCtrl); 
listCtrl.$inject = ["$scope", "$state", "$timeout", "listService", "$rootScope"]; 

function listCtrl($scope, $state, $timeout, listService, $rootScope) { 
    this.$scope= $scope; 

    $scope.service=listService; 
    //some other definitions 

    $scope.items = $scope.service.getPage(%function_ARGUMENTS%); 

} 

这里的服务是如何定义的:

angular.module("test").service("listService", listService); 
listService.$inject = ['$state', '$rootScope']; 

function listService($state, $rootScope) { 
    function getPage(%function_ARGUMENTS%) { 
    //getPage function definition goes here 
    } 
} 

现在,出于某种原因,我得到的错误:

Cannot read property 'getPage' of undefined

我想不出什么migh不会造成这种情况。
$scope是如何定义的问题?如果是,那么假设this.$scope=$scope不能修改,那么这样做的正确方法是什么。

编辑:修复了问题中的复数错字。我的程序中没有这样的打字错误,这是我在SO打字时犯的一个错误。

+0

您在'$ scope.services中有错字。getPage(%function_ARGUMENTS%);'它必须是'$ scope.service.getPage(%function_ARGUMENTS%);' –

+0

我修复了问题中的错字,错字不是导致我主程序错误的原因。 – ChaoticTwist

+0

我也发布了答案,反正你发现问题很重要。 –

回答

1

由于您已定义$scope.service,因此使用$scope.services时会出现其他“s”错误。因此,使用正确的变量

$scope.items = $scope.service.getPage(%function_ARGUMENTS%); 

但是,您将小号,直到收到其他错误作为函数getPage与退换货服务对象相关联。

function listService($state, $rootScope) { 
    this.getPage = function() { 
    //getPage function definition goes here 
    } 
} 

OR,

function listService($state, $rootScope) { 
    function getPage() { 
    //getPage function definition goes here 
    } 

    this.getPage = getPage; 
} 
+0

修复了问题中的错字。你的回答有帮助。我没有注册该服务的功能。谢谢。 :) – ChaoticTwist

1
angular.module("test").factory("listService", listService); 
listService.$inject = ['$state', '$rootScope'];  

function listService($state, $rootScope) { 
    return { 
     function getPage(%function_ARGUMENTS%) { 
     //getPage function definition goes here 
     } 
    } 
} 

上面只写你的服务功能。

1

我也注意到: $ scope.items = $ scope.services.getPage(%function_ARGUMENTS%);

应该是: $ scope.items = $ scope.service.getPage(%function_ARGUMENTS%);

$ scope.service在该行上复数化时,应该是单数。

以及您正在使用服务服务,这是一个构造函数。因此,您需要使用此关键字引用您的属性。角度服务方法使用new关键字在内部创建对象。你可以尝试一个工厂:

angular.module("test") 
    .factory("listService", listService); 
    listService.$inject = ['$state', '$rootScope']; 

    function listService($state, $rootScope) { 
    function getPage(%function_ARGUMENTS%) { 
     //getPage function definition goes here 
    } 
    return { 
     getPage: getPage 
    }; 
} 

这更类似于你有什么,你不需要使用this关键字,因为它不是一个构造函数。

希望这会有所帮助!

干杯