The issue with AngularJS Routing is that it fails to refresh the menu items when the URL and views are being

My current project involves implementing token-based authentication using the MEAN stack. The goal of my application is to display different menu items based on whether a user is logged in or not. When there is no token present, the menu should show options for Home, Signin, and Signup. Once a user is logged in and a token is generated, the menu should update to show Home, Me, and Logout. While the server-side functionality for Signin, Signup, and Logout is functioning correctly with proper URL redirection and view rendering, I am facing an issue with the dynamic updating of the Menu items. The menu only refreshes when I manually trigger a page refresh. I am seeking assistance in resolving this issue.

Below are snippets from my Index.html file (Includes omitted for brevity):

<body ng-app="app">
    <div class="navbar navbar-inverse navbar-fixed-top" role="navigation" data-ng-controller="authCtrl">
       <!-- data-ng-controller="authCtrl" -->
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".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" href="#/">Angular Restful Auth</a>
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li><a ng-href="#/">Home</a></li>
                    <li data-ng-show="token"><a ng-href="#/me">Me</a></li>
                    <li data-ng-hide="token"><a ng-href="#/login">Signin</a></li>
                    <li data-ng-hide="token"><a ng-href="#/register">Signup</a></li>
                    <li data-ng-show="token"><a ng-click="logout()">Logout</a></li>                    
                </ul>
            </div><!--/.nav-collapse -->
        </div>
    </div>
    <div class="container" ng-view="">
    </div> <!-- /container -->
    </body>

The accompanying app.js script contains the configuration details:

'use strict';

var app = angular.module('app', ['ngRoute', 'authControllers', 'authServices']);
var authControllers = angular.module('authControllers', []);
var authServices = angular.module('authServices', []);

var options = {};
options.api = {};
//dev URL
options.api.base_url = "http://localhost:3000";

app.config(['$locationProvider', '$routeProvider',
function($location, $routeProvider) {
  $routeProvider.
  when('/', {
    templateUrl: 'partials/home.html',
    controller: 'authCtrl'
  }).
  when('/login', {
    templateUrl: 'partials/signin.html',
    controller: 'authCtrl'
  }).
  when('/register', {
    templateUrl: 'partials/signup.html',
    controller: 'authCtrl'
  }).
  when('/me', {
    templateUrl: 'partials/me.html',
    controller: 'authCtrl'
  }).
  otherwise({
    redirectTo: '/'
  });
}]);
app.config(['$httpProvider', function ($httpProvider) {
  $httpProvider.interceptors.push('TokenInterceptor');
}]);
app.run(function($rootScope, $location, $window, AuthenticationService) {
  $rootScope.$on("$routeChangeStart", function(event, nextRoute, currentRoute) {
    //redirect only if both isAuthenticated is false and no token is set
    if (nextRoute != null && nextRoute.access != null && nextRoute.access.requiredAuthentication
      && !AuthenticationService.isAuthenticated && !$window.sessionStorage.token) {
        $location.path("/login");
      }
    });
  });

Lastly, the authControllers.js file includes the necessary controller functions:

authControllers.controller('authCtrl', ['$scope', '$location', '$window', 'UserService', 'AuthenticationService',
function authCtrl($scope, $location, $window, UserService, AuthenticationService) {
  //Admin User Controller (login, logout)
  $scope.logIn = function logIn(username, password) {
    if (username !== undefined && password !== undefined) {
      UserService.logIn(username, password).success(function(data) {
        AuthenticationService.isLogged = true;
        $window.sessionStorage.token = data.token;
        $location.path("/me");
      }).error(function(status, data) {
        console.log(status);
        console.log(data);
      });
    }
  }
  $scope.token = $window.sessionStorage.token;
  $scope.me = function() {
    UserService.me(function(res) {      
      $scope.myDetails = res;
    }, function() {
      console.log('Failed to fetch details');
      $rootScope.error = 'Failed to fetch details';
    })
  };
  $scope.logout = function logout() {
    if (AuthenticationService.isAuthenticated) {
      UserService.logOut().success(function(data) {
        AuthenticationService.isAuthenticated = false;
        delete $window.sessionStorage.token;
        $location.path("/");
      }).error(function(status, data) {
        console.log(status);
        console.log(data);
      });
    }
    else {
      $location.path("/login");
    }
  }
  $scope.register = function register(username, password, passwordConfirm) {
    if (AuthenticationService.isAuthenticated) {
      $location.path("/me");
    }
    else {
      UserService.register(username, password, passwordConfirm).success(function(data) {
        $location.path("/login");
      }).error(function(status, data) {
        console.log(status);
        console.log(data);
      });
    }
  }
}]);

Answer №1

$scope.accessToken = $window.sessionStorage.token;

Make sure you update your scope variable each time and call apply explicitly if you are not in the digest loop to bind the token to the storage property.

Answer №2

After experimenting with various methods, I discovered a more efficient approach to handle global changes in one shot. By injecting $rootScope into my controller and assigning the SessionStorage token value to it, I was able to streamline the process without having to update $scope variables in multiple locations.

authControllers.controller('authCtrl', ['$rootScope','$scope', '$location', '$window', 'UserService', 'AuthenticationService',
function authCtrl($rootScope,$scope, $location, $window, UserService, AuthenticationService) {
$rootScope.token = $window.sessionStorage.token;
}]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In JavaScript, the checkboxes in all columns of a table with over 200 rows can be set, but only the checkboxes in the rows

Seeking help to implement toggle buttons for checkboxes on a page with a large table fetched from an external system. The table can have over 200 rows or more. Currently, I am facing an issue where I can only access and manipulate the visible checkboxes o ...

Invisible and Unrestricted automatic playback

Why is auto play muted in both Firefox and Chrome? How can we code it so that browsers don't block it? Here's the code I'm using: <audio id="audio1" src="https://notificationsounds.com/storage/sounds/file-sounds-1217-relax ...

Techniques for incorporating a variable into the value field in JavaScript

let y = data[1]; cell1.innerHTML ='<input id="text" type="text" value= "'y'"/>' ; This snippet of code does not render any content when attempting to pass the variable, but if you provide a specific value like "h", it will displa ...

Tips for integrating new channels and categories using a Discord bot

Hey there! I'm trying to add channels and categories, but I can't seem to get the function ".createChannel" working. The console keeps telling me that the function doesn't exist. I've been referencing the documentation at https://discor ...

Is the security of Angular's REST authentication reliable?

My goal is to establish a secure connection with a REST service using Angular. I have come across the official method, which involves setting the authentication ticket like this: $httpProvider.defaults.headers.common['Authorization'] = 'dhf ...

The module in Node.js is unable to be loaded

Dealing with a common problem here. Despite trying to reinstall npm, deleting node_modules files and package-lock.json, the issue persists. The console output is as follows: node:internal/modules/cjs/loader:1080 throw err; ^ Error: Cannot find module &apo ...

Display a complete calendar with the date picker on a webpage

Currently experimenting with React to build a straightforward application. Admiring the appearance of full calendars from these date pickers (once clicked): Material-UI React-Toolbox Wondering if it's feasible to present the full calendar directly ...

Using cfajaxproxy in conjunction with URL rewriting capabilities

I have successfully integrated the cfajaxproxy tag, but encountered an issue with the cfc's location in the root directory of my site. When accessing a page within the root directory through a rewritten URL (e.g. mysite.com/one/two/ -> mysite.com/ ...

My website using Dynamic Ajax technology is currently experiencing heavy traffic due to the number of getScript

I am facing an issue with my dynamic website where all links fetch new sections via ajax requests from other pages and replace the current section. The problem I encounter has two main aspects. When loading a new div from an Ajax get request, some sections ...

Integrating Dynamics CRM with an External Source to Trigger Workflows

Scenario: Imagine a scenario where you want to trigger an existing workflow or a custom action from a webpage located outside the CRM Dynamics environment, such as MS CRM 2011-2013-2015-2016 and 365. Potential Solution: One possible solution could be to ...

attach an event listener for the click event

I have a button set up like this Inside index.html: <body> <section> <button id="open-file">Open File</button> ...(series of other similar buttons)... </section> </body> <script> requir ...

As you scroll, a box blocks off half of the screen

Hey everyone, I could really use your assistance! I'm working on developing a javascript code and here is the idea - if anyone can contribute to it. It's like a social media platform where users enter the site and the is_user_logged_in parameter ...

Encountering an Issue while Deploying a create-react-app to Heroku

Despite trying various online remedies, I am still encountering an error while attempting to deploy a simple React.js app on Heroku. The app successfully builds when I execute git push heroku master, but upon opening it, I consistently receive an applicati ...

Can the mui dialog actions button be activated using CTRL + S?

Is it feasible to enable my users to save content in a MuI dialog by pressing CTRL + S? ...

Delaying the search in Jquery until the input is finalized

Is there a way to delay the search trigger until the user finishes typing? I'm utilizing a function created with mark.js () which initiates the search as the user types, resulting in jumping to the first result during the search. However, the issue is ...

Tips for implementing advertisements through a content management system or JavaScript

After reviewing a discussion on how to dynamically change code on clients' websites for serving ads, I am in search of an easy-to-implement solution. The code is frequently updated as we experiment with different ad networks like Adsense. Ideally, I w ...

Send the appropriate data once the response has been completed

My Express.JS server has multiple res.json responses. In order to conduct statistics, logging, and debugging, I am looking to capture the response payload using a universal hook. While I have come across the finish event res.on('finish'), I am s ...

How can I identify when a form has been edited in order to update the database with those changes only?

Currently, I have a form with over 50 fields. While I've successfully implemented functionality for inserting, selecting, and deleting records, I'm struggling with updating a record. Specifically, if a user only updates one or two fields out of t ...

The functionality of Angular.js route seems to be malfunctioning

Hello friends, I am fairly new to working with AngularJS and have been experimenting with angular Route. However, I encountered an issue where clicking on #/home resulted in a strange URL appearing here. Oddly enough, the default otherwise condition seems ...

The Vue DevTools are functioning as expected, but there seems to be an issue

Encountering a peculiar issue where the value displayed in Vue DevTools is accurate, matching what is expected in my data. When I first click on the "Edit" button for an item, the correct value appears in the browser window as intended. However, upon clic ...