我尝试使用用户的 uid
将一些内容插入到我的 Firebase 数据库中,但由于某种原因,结果未定义。看一下下面的代码:
页面加载时设置用户数据信息(authData
)的主 Controller :
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();
});
}]);
处理身份验证状态并在我的 Controller 之间共享它的服务:
flickrApp.service('shared', function() {
var authentication = false;
return {
getAuth: function () {
return authentication;
},
setAuth: function (auth) {
authentication = auth;
}
};
});
这是它不起作用的地方,在我的标签 Controller 中。 $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});
}
}]);
最佳答案
我认为问题是,对 ref 的分配是在 $scope.authData 的数据设置在 $watch 中之前完成的。尝试将您的代码更改为:
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});
}
}]);
关于javascript - 尽管在 $watch 函数中设置了 $scope 变量,但 $scope 变量未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28380325/