我有两个控制器和一个工厂。我正在使用angular-devise模块进行身份验证。
UserFactory.js
myApp.factory('Userfactory', function(Auth,$location){
var Userfactory = {}
Userfactory.user = []
Userfactory.active = false
Userfactory.isLogged = function(){
if(!Userfactory.active[0]){
return Auth.currentUser().then(function(user) {
Userfactory.user.push(user)
Userfactory.active = angular.copy(true)
}, function(error) {
});
}
}
return Userfactory;
})
UserController.js
myApp.controller("userController",function($scope,Userfactory){
Userfactory.isLogged().then(function(){
$scope.active = Userfactory.active;
})
}
NavController.js
myApp.controller("navController", function navController(Userfactory){
this.user = Userfactory.user;
this.active = Userfactory.active;
})
当isLogged更新值时,导航控制器中的UserFactory.active不会更新,因为该值正在重置(打破绑定),而在用户控制器中,值是通过promise分配的,因此它获取最新值。我怀疑的是如何设法让它在两个地方都有效,这意味着如何在不破坏绑定的情况下分配值。
一种解决方法是将Userfactory.active声明为数组,并将值推送到true或false,但是寻找更好的方法,任何帮助都会很有用。
答案 0 :(得分:3)
我建议你使用 model 对象来包装你需要绑定的所有变量/属性。
myApp.factory('Userfactory', function(Auth,$location){
var Userfactory = {}
Userfactory.model = {
user: undefined,
active: false
};
Userfactory.isLogged = function(){
if(!Userfactory.active[0]){
return Auth.currentUser().then(function(user) {
Userfactory.model.user = user;
Userfactory.model.active = true;
}, function(error) {
});
}
}
return Userfactory;
})
然后在您的控制器上:
myApp.controller("userController",function($scope,Userfactory){
Userfactory.isLogged().then(function(){
$scope.userModel = Userfactory.model;
// and on the UI use: userModel.active
})
}
myApp.controller("navController", function navController(Userfactory){
this.userModel = Userfactory.model;
// then access it like: this.userModel.active
})