i would reload variable in controller that use for navbar.
I have controller for each view. I use a controller, loginCtrl, to login after i logged i would reload the var set in "rootController".
I use a variable for ng-if to switch button login and logout in navbar, but this variable (in rootController) is getting to call a factory function.
The problem are that variable one time is set don't change when i change value of factory. The solution is reload only rootController to reset var, search to internet i found $route.reload(). I've create a function in rootController and i use it so:
$rootScope.reload = function(){ $timeout(function () {
$route.reload();
}, 0);
};
but when i call in other controller the app loads infinity.
How resolve it?
EDIT:
angular.module('appModule',[])
.controller('AppCtrl',function ($scope,$rootScope,UserLogged){
$scope.isLogged = UserLogged.isLogged();
$scope.user = UserLogged.get();
});
.config(...) // To configure route, one route have loginCtrl as controller
.controller('loginCtrl',function($scope,$http,UserLogged){
$http.get(..).sucess(function(data){UserLogged.set(data)})
// call a WS to setup the factory UserLogged
)
.factory('UserLogged',function(){
var userLogged
var isLogged
// set and get method
}
All work fine but when i update the isLogged var in factory the app don't update $scope.isLogged in AppCtrl. The solution are reload AppCtrl to recall UserLogged.get() and reset $scope.isLogged with the new value.
SOLVED:
@ rtvalluri Thanks
// App control
$scope.$on('loginLogout',function(){
$scope.isLogged = UserLogged.isLogged();
$scope.userLogged = UserLogged.get();
});
// loginCtrl
$http.get(..).sucess(function(data){
UserLogged.set(data);
$scope.$emit('loginLogout');
})
You can try emitting two events for login and logout, with which you can update variable in rootController without refreshing it
In your navbar
<button ng-if="!isLoggedIn">Login</button>
<button ng-if="isLoggedIn">Logout</button>
If mainController is the rootController and login and logout are the two different functions in two different controllers,
then keep listening in rootController using:
$scope.$on('login',function(event,data){
//assume 'isLoggedIn' is the boolean value
$scope.isLoggedIn = data;
});
$scope.$on('logout',function(event,data){
$scope.isLoggedIn = data;
});
Try emitting 'login' event from Login Controller
//on successful login, trigger below event
$scope.$emit('login',true);
and in Logout Controller
//on successful logout, trigger below event
$scope.$emit('logout',false);
Note: Above approach works only if mainController is the parent controller for other controllers, otherwise try emitting events on $rootScope instead of $scope
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.