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

时间:2015-02-07 09:03:37

标签: javascript angularjs service angularfire watch

我尝试使用用户的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未定义(因此我可以&#39} ; t访问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});
    }
}]);

1 个答案:

答案 0 :(得分:1)

我认为问题是,在$ 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});
    }
}]);