I have developed an angular project that includes a navigation bar. I would like the navigation bar to automatically update when users log in. I tried using ng-show
and ng-hide
to control it, but unfortunately, it doesn't seem to work. Can someone help me with this issue? I'm not sure if I have written the code incorrectly. I hope my question is clear, as English is not my first language.
<nav class="navbar navbar-default" role="navigation" ng-controller="UserCtrl">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse"
data-target="#example-navbar-collapse">
<span class="sr-only">Toggle Navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" ui-sref="index">Wishing Wall{{username}}</a>
</div>
<div class="collapse navbar-collapse" id="example-navbar-collapse">
<ul class="nav navbar-nav">
<li class="active"><a ui-sref="index">Home</a></li>
<li ng-hide="isLogined"><a ui-sref="user.login">Login</a></li>
<li ng-show="isLogined"><a ui-sref="user.info">Profile</a></li>
<li ng-show="isLogined"><a ui-sref="user.wish">My Wishes</a></li>
<li ng-show="sex == 'female'"><a ui-sref="user.putwish">Make a Wish</a></li>
<li ng-show="isLogined"><a ng-click='doLogout()'>Logout</a></li>
</ul>
</div>
</nav>
<div class="container-fluid" ui-view>
</div>
Here is my controller's code:
app.controller('UserCtrl', ['$scope', '$state', 'LogoutService', function($scope, $state, LogoutService) {
if(sessionStorage.getItem('username')) {
$scope.isLogined = true;
$scope.username = sessionStorage.getItem('username');
if(sessionStorage.getItem('sex') == 'male') {
$scope.sex = 'male';
} else {
$scope.sex = 'female';
}
} else {
$scope.isLogined = false;
}
$scope.doLogout = function() {
LogoutService.doLogout();
sessionStorage.removeItem('username');
sessionStorage.removeItem('sex');
$state.go('index');
};
}]);
app.controller('LoginCtrl', ['$scope', '$state', 'LoginService', function($scope, $state, LoginService) {
$scope.doLogin = function() {
var data = {
username: $scope.username,
password: $scope.password
};
LoginService.doLogin(data)
.success(function(data, status){
if(status === 200) {
sessionStorage.setItem('username', data.user.username);
sessionStorage.setItem('sex', data.user.sex);
$state.go('index');
}
});
};
}]);