为什么我无法访问$rootScope
,特别是RegistrationController中的currentUser对象和signedIn()
函数?我试图按照教程的例子,我能够成功地设置服务(认证)中的$rootScope.currentUser
变量,但是当我尝试从另一个控制器(RegistrationController)访问它时,我无法访问它。
我的理解是,$rootScope
是一种全局变量,可以从所有的应用程序访问,这是正确的吗?
myApp.controller('RegistrationController',
function($scope, $firebaseAuth, $location, Authentication, $rootScope){
$scope.login = function() {
Authentication.login($scope.user)
.then(function(userReturned){
console.log('registration.js: logged in user '+userReturned.uid);
//console.log('registration.js: $rootScope.currentUser ahora es... ');
//console.log($rootScope.currentUser);
$location.path('/meetings');
})
.catch(function(error) {
$scope.message = error.toString();
});
} //login
}); //RegistrationController
myApp.factory('Authentication',
function($firebase, $firebaseAuth, FIREBASE_URL, $location, $rootScope) {
// using $firebaseAuth instead of SimpleLogin
var ref = new Firebase(FIREBASE_URL);
var authObj = $firebaseAuth(ref);
var myObject = {
login : function(user) {
return authObj.$authWithPassword({
email: user.email,
password: user.password
})
.then(function(authData){
console.log('authentication.js: logged in user '+ authData.uid);
var userRef = new Firebase(FIREBASE_URL + 'users/' + authData.uid);
var userObj = $firebase(userRef).$asObject();
userObj.$loaded().then(function() {
$rootScope.currentUser = userObj;
});
$rootScope.$broadcast('$firebaseAuth:authWithPassword',authData); // avisa al scope
return authData;
});
}, //login
signedIn: function() {
//console.log(authObj);
//console.log('authentication.js: signedIn function called and returned '+ (authObj.user != null));
return authObj.user != null;
} // signedIn
} //myObject
// add signedIn to the $rootScope
$rootScope.signedIn = function() {
return myObject.signedIn();
}
return myObject;
});
首先,提供一些plunkr或js小提琴示例。另外,写任何一个作用域(以及rootScope也是如此)标量(通过对象执行,例如$ scope.model.XXX)并不是一个好主意。另一件事:在rootScope中根本不存储任何内容,而是将数据存储在服务中:您可以从任何“任何东西”(即控制器,指令等)访问数据。是的,rootScope在AngularJS中具有全局作用域(如全局变量)。你还记得使用它们不好吗?与rootScope相同的情况。不要用它来存储变量。 – 2015-02-08 21:40:06
嗨@Sharikov弗拉迪斯拉夫,感谢您的评论。在询问之前,我做了一些调查,并且发现了你提到的有关服务的内容,但是我正在按照他们使用$ rootScope的教程进行操作,看起来很奇怪,我无法读取存储在那里的值。我知道使用全局变量不是一个好主意:) 我对Plunker并不是很熟悉,但我会试一试并用结果进行编辑。 – 2015-02-08 23:01:29