繁体   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