尽管在 $watch 函数中设置了 $scope 变量但未定义

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

我正在尝试使用用户的 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});
    }
}]);