I have a UserService
angular.module('mango.services', [])
.factory('UserService', function() {
var user = {
id: null,
name: 'anonymous.'
};
function getUser(){
return user;
}
function setUser(val){
user = val;
}
return {
getUser: getUser,
setUser: setUser,
}
});
a NavbarController
.controller('NavbarController', ['$scope','$location','UserService', function($scope, $location, UserService){
$scope.isActive = function (viewLocation) {
return viewLocation === $location.path();
};
$scope.username = UserService.getUser().name;
}])
and a UserController where I have registerUser and loginUser functions.
.controller('UserController', ['$scope', '$http', 'UserService', function($scope, $http, UserService) {
$scope.loginUser = function(){
$http.post('/api/1.0/user/authenticate', $scope.user)
.success(function(data,status,headers,config){
if (data["valid"] === true) {
UserService.setUser(data.user);
} else {
$scope.flashes = data.flashes;
$scope.user.password = "";
}
})
}
and the HTML
<li ng-switch="username">
<a ng-class="{ active: isActive('/user/login')}" href="#/user/login" ng-switch-when="anonymous."><i class="fa fa-sign-in"></i> Sign in</a>
<a ng-class="{ active: isActive('/user/logout')}" href="#/user/logout" ng-switch-default><i class="fa fa-sign-out"></i> Sign out</a>
</li>
As you can see I'm trying to set the user of UserService if data.valid is true.
The server is returning a valid json object.
But the username value in NavbarController remains "anonymous." .
I'm not very experienced in JS, but I read something about broadcast and watch. I believe this might be the right approach. But maybe there's a better one.
I believe why it's not working is because the factory returns a singleton. But then using a factory is pointless.
So essentially what I want is, if credentials valid set user.name user.id client-app-wide. Later it should go through an "check if client user is valid" service. My session cookie is encrypted. But that's out of scope of the question.
All I need right now is to set the app's or rather the NavbarController's user data from UserController. How do I do that so it also updates the DOM aka ng-switch getting a different value.