$scope变量未定义,尽管它是在$watch函数内部设置的

$scope variable being undefined despite being set inside a $watch function

本文关键字:watch 函数 内部 设置 变量 scope 未定义      更新时间:2023-09-26

我试图使用用户的uid将一些内容插入到Firebase数据库中,但由于某种原因,它没有定义。看看下面的代码:

页面加载时设置用户数据信息(authData)的主控制器:

flickrApp.controller('mainCtrl', ['$scope', '$rootScope', '$firebase', 'Auth', 'shared', function($scope, $rootScope, $firebase, Auth, shared) {
    Auth.$onAuth(function(authData) {
        shared.setAuth(authData);
        $scope.authData = shared.getAuth();
    });
}]);

处理身份验证状态并在我的控制器之间共享的服务:

flickrApp.service('shared', function() {
    var authentication = false;
    return {
        getAuth: function () {
            return authentication;
        },
        setAuth: function (auth) {
            authentication = auth;
        }
    };
});

这是它不起作用的地方,在我的标签控制器中。$scope.authData$watch函数中设置正确,但当我尝试在var ref行中使用它时,它表示$scope.authData未定义(因此我无法访问uid)。我不明白为什么这不起作用。

我是否也必须将$apply与观察程序功能一起使用,或者哪里出了问题?

flickrApp.controller('tagsCtrl', ['$scope', '$rootScope', '$firebase', 'shared', function($scope, $rootScope, $firebase, shared) {
    $scope.tagsList = [];
    $scope.shared = shared;
    $scope.$watch('shared.getAuth()', function(authData) {
        $scope.authData = authData;
        console.log($scope.authData);
    });
    var ref = new Firebase ('https://flickr.firebaseio.com/users/' + $scope.authData.uid);
    var sync = $firebase(ref);
    $scope.addTag = function(tag) {
        $scope.tagsList.push(tag);
        sync.$set({favoriteTags: $scope.tagsList});
    }
}]);

我认为问题是,在$watch中设置$scope.authData的数据之前,对ref的赋值已经完成。尝试将您的代码更改为:

flickrApp.controller('tagsCtrl', ['$scope', '$rootScope', '$firebase', 'shared', function($scope, $rootScope, $firebase, shared) {
    $scope.tagsList = [];
    $scope.shared = shared;
    var ref,sync;
    $scope.$watch('shared.getAuth()', function(authData) {
        $scope.authData = authData;
        console.log($scope.authData);
        if($scope.authData){
            ref = new Firebase ('https://flickr.firebaseio.com/users/' + $scope.authData.uid);
            sync = $firebase(ref);
        }
    });

    $scope.addTag = function(tag) {
        $scope.tagsList.push(tag);
        sync.$set({favoriteTags: $scope.tagsList});
    }
}]);