I gather several possible solutions none of them work for me. Can someone tell which part has error.
This is the logout function I am working on, the icon should disappear if user click logout and back to login page, but now it only lead to login page. Icon is still there because the function didn't trigger. Everything works only AFTER I click the button in login page,
navigation.service.js
(function() {
angular
.module('TheApp')
.service('authentication', ['$window', function($window) {
var saveToken = function(token) {
$window.localStorage['auth-token'] = token;
}
var getToken = function() {
return $window.localStorage['auth-token'];
}
var logout = function() {
$window.localStorage.removeItem('auth-token');
//delete $window.localStorage['auth-token'];
//$window.localStorage.clear();
}
var isLoggedIn = function() {
var token = getToken();
//Get token from storage If token exists get payload, decode it, and parse it to JSON
if (token) {
let payload = JSON.parse($window.atob(token.split('.')[1]));
return payload.exp > Date.now() / 1000;
} else {
return false;
}
}
return {
saveToken: saveToken,
getToken: getToken,
isLoggedIn: isLoggedIn,
logout: logout
};
}])})();
navigation.directive.js
(function() {
angular
.module('TheApp')
.directive('navigation', navigation);
function navigation() {
return {
restrict: 'EA',
templateUrl: './common/directives/navigation/navigation.template.html',
controller: 'navigationCtrl as navvm'
};
}})();
navigation.controller.js
(function() {
angular
.module('TheApp')
.controller('navigationCtrl', ['$location', 'authentication', '$window', function($location, authentication, $window) {
console.log("enters navigation controller");
var vm = this;
vm.isLoggedIn = authentication.isLoggedIn();
vm.logout = function() {
console.log('test if the link work');
authentication.logout();
$location.path('/login');
};
}]);})();
navigation.template.html
<ul class="nav navbar-nav navbar-right">
<li ng-show="navvm.isLoggedIn">
<a href="" ng-click="navvm.logout()">
<span aria-hidden="true" class="glyphicon glyphicon-log-out"></span></a></li>
</ul>
Thanks.
Solution(UPDATE):
A careless situation, I omit to put the controller link inside index.html (main template page). So if anyone working on the similar project, the code above should works without errors.