I have an angularJS app which includes login functionality handled in the backend with express + passport; this was up until recently working fine but I've changed some things and now it is not working and I don't know how to fix my problem..
After logging in on the login page you are meant to be redirected to the index and the $scope.cUser.userName variable should have your current username however the page doesn't update the scope for userName until I actually refresh(f5) the whole page! Interestingly, the $scope.cUser.created value does update and render correctly on the page.. I can confirm that express is correctly delivering the username to angular in JSON
login method in login controller:
$scope.login = function(){
$http.post('/users/login', {
username: $scope.user.username,
password: $scope.user.password
})
.success(function(user){
toaster.pop('success', "Success!", "You have been logged in");
$rootScope.$broadcast('loggedIn', user);
$location.path('/');
})
.error(function(user){
toaster.pop('error', 'We couldn\'t log you in!', 'The provided user credentials are incorrect');
$location.url('/login');
});
};
check if logged in on app run:
$http.get('/users/loggedin').success(function(user){
if (user.loggedin !== false){
$rootScope.$broadcast('loggedIn', user);
} else {
$rootScope.$broadcast('loggedOut');
}
});
and this is my 'mainController' which operates on the whole website outside of the ng-view:
$scope.cUser = {};
$scope.$on('loggedIn', function(event, user){
$timeout(function(){
$scope.$apply(function(){
$scope.cUser.loggedIn = true;
$scope.cUser.userName = user.username;
$scope.cUser.created = user.created;
});
});
});
$scope.$on('loggedOut', function(event){
$scope.cUser.loggedIn = false;
$scope.cUser = {};
$scope.$apply();
});
Logging out functionality works as expected, but the $scope.cUser.userName is not being rendered on the page! Please help!
$scope.$apply();it could break execution if$applyis already in progress..tryif(!$scope.$$phase) $scope.$apply();$timeoutanyway, which itself was just as pointless since the event is fired from inside Angular in a success handler. So all in all both the apply and the timeout are pointless and are a quite common anti-pattern in Angular.