2017-02-23 6 views
0

私は古いプロジェクトに新しい機能を追加する角度のあるプロジェクトに取り組んでいます。
コントローラにサービスを登録しようとしていますが、コントローラがサービス内の機能を見つけることができないエラーが発生しています。コントローラのanglejsからサービスにアクセスできない

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

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

はここでサービスが定義されている方法です

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%); 

} 

(。私はそれが標準的な方法ではないですけど、私は、アプリケーション全体がないため、これに従わなければならない)私のコントローラが定義されている方法です

さて、何らかの理由で、私はエラーを取得する:

Cannot read property 'getPage' of undefined

私がmighかを把握することはできませんこれを引き起こしている。
$scopeの定義方法に問題はありますか?はいの場合、this.$scope=$scopeとすると、これを行う正しい方法は何も変更できません。

EDIT:質問に複数のタイプミスが修正されました。私は自分のプログラムでそのタイプミスをしていない、それは私がSOに入力している間に間違いだった。

+0

「$ scope.services」に誤字があります。'$ scope.service.getPage(%function_ARGUMENTS%);' –

+0

私はこの問題のタイプミスを修正しました。私のメインプログラムでは、タイプミスはエラーの原因ではありません。 – ChaoticTwist

+0

私はあまりにも、とにかく、あなたが問題が重要であることを考え出した答えを掲載しました。 –

答えて

1

$scope.serviceと定義されているようにエラーが発生するのは、$scope.servicesに「s」が追加されています。だから、リターンサービスオブジェクトに関連付けられて機能getPageとして別のエラーを取得するまで、正しい変数

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

しかし、あなたは意志を使用しています。

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は、単数でなければならないときにその行に複数化されています。

同様に、コンストラクタ関数であるサービスサービスを使用しています。したがって、thisキーワードでプロパティを参照する必要があります。角度サービスメソッドは、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キーワードを使用する必要はありません:あなたは、工場を試みることができます。

希望すると便利です。

乾杯

関連する問題