簡體   English   中英

調用初始化函數時無法識別$ scope變量

[英]$scope variable isn't recognized when calling initialization function

我有以下代碼,我想在其中接收當前用戶的所有文本,並在頁面加載時在屏幕上顯示它們:

angular.module('eddieApp')
    .controller('MainController', function ($scope, Principal, TextService) {

        $scope.texts = [];

        Principal.identity().then(function(account) {
            $scope.account = account;
            $scope.isAuthenticated = Principal.isAuthenticated;
        });

        $scope.findByUser = function(){
            TextService.findByUser($scope.account.login).success(function(data){
                $scope.texts = data;
            });
        };

        // receive all notes from current user
        $scope.$watch(function(scope) { return scope.account; },
                      function()      { $scope.findByUser(); });


    });

問題是它可以工作,但是我不明白為什么這是使其工作的唯一方法。

我試圖這樣調用函數$scope.findByUser()

angular.module('eddieApp')
    .controller('MainController', function ($scope, Principal, TextService) {

    $scope.texts = [];

    Principal.identity().then(function(account) {
        $scope.account = account;
        $scope.isAuthenticated = Principal.isAuthenticated;
    });

    $scope.findByUser = function(){
        TextService.findByUser($scope.account.login).success(function(data){
            $scope.texts = data;
        });
    };

    $scope.findByUser();

});

但我收到一個錯誤, $scope.account.login無法識別$scope.account.login

另外,我嘗試將指令ng-init="findByUser()"放入html代碼中,但是同樣,我收到相同的錯誤消息,指出無法識別$scope.account.login

最終,我使它可以使用$watch函數工作,但是我不明白為什么前兩種方法不起作用,因為它們更易於理解,因此我傾向於使用它們代替$watch

它的工作原理是因為你的$watch確保$scope.account運行之前定義$scope.findByUser

在您沒有監視的示例中, findByUser立即執行,並嘗試使用未定義的$scope.account login屬性。

如果擁有用戶帳戶是findByUser的先決條件,並且視圖中沒有可以立即調用的用戶帳戶,則在您的then塊中調用findByUser可能更有意義,這將避免需要$watch

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM