Hello, I am currently searching for a solution to dynamically modify the navigation links within the navigation bar based on whether a user is logged in or not. Of course, a logged-in user should have access to more pages.
I have developed a UserService that utilizes the ng-token-auth module (https://github.com/lynndylanhurley/ng-token-auth) and includes a boolean variable to store the login state. Here is an example of the service:
angular.module('app')
.run(function($rootScope, $location, userService) {
$rootScope.$on('auth:login-success', function(ev, user) {
userService.setLoggedIn(true);
$location.path('/on/dashboard');
});
})
.factory('userService', function($auth) {
var service = {};
service.loggedIn = false;
service.submitLogin = submitLogin;
service.setLoggedIn = setLoggedIn;
service.getLoggedIn = getLoggedIn;
return service;
function submitLogin(params) {
$auth.submitLogin(params)
}
function setLoggedIn(bool) {
service.loggedIn = bool;
}
function getLoggedIn() {
return service.loggedIn;
}
});
This was how my directive was structured:
.directive('agNavigation', function(userService) {
if(userService.getLoggedIn()){
return {
restrict: 'AE',
replace: true,
templateUrl: '/views/userNavigation.html'
}
}else{
return {
restrict: 'AE',
replace: true,
templateUrl: '/views/navigation.html'
}
}
});
After logging in, the view successfully switches to the dashboard but the directive does not update as it is not called again. To address this issue, I attempted to use the $watch
function, but I am facing challenges with its implementation. Here is what I tried:
.directive('agNavigation', function(userService) {
var navUrl = '';
if(userService.getLoggedIn()){
navUrl = '/views/userNavigation.html';
}else{
navUrl = '/views/navigation.html';
}
return {
restrict: 'AE',
replace: true,
templateUrl: navUrl,
link: function postLink(scope, element, attrs, controller) {
scope.$watch(function() {
return userService.getLoggedIn();
}), function(newValue, oldValue) {
if(newValue){
navUrl = '/views/userNavigation.html';
}else{
navUrl = '/views/navigation.html';
}
}
}
}
});
As I am relatively new to AngularJS, any guidance or suggestions on alternative approaches would be greatly appreciated.