Navigating efficiently with AngularJS directives

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.

Answer №1

userService.getLoggedIn() will cause a compilation error in the directive if you follow the code provided in your initial example. It is essential to refactor that code to the templateUrl function and return the URL based on certain conditions.

Code

.directive('agNavigation', function(userService) {
      return {
        restrict: 'AE',
        replace: true,
        templateUrl: function(){
           if(userService.getLoggedIn()){
             return '/views/userNavigation.html';
           }
            return '/views/navigation.html';
        }
      }
  });

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

Having trouble with the Bootstrap dropdown not activating the click event?

My issue involves a Bootstrap dropdown where the click event is not triggering. I'm curious about why the click event won't trigger and if there's a solution available to fix this problem. <div class="dropdown d-inline-block"> ...

What is the best way to extract the text from a class only when it is nested within a particular header tag?

const request = require ('request'); const cheerio = require('cheerio'); const fs = require ('fs'); request("http://kathmandupost.ekantipur.com/news/2018-08-31/bimstec-summit-multilateral-meet-underway.html", (error, response ...

Explore within the <li> element using jQuery

Need assistance on how to search within the li element. The li list consists of employee names in the format [surname,firstname]: Venkata,Anusha Raju,Suma Here is the HTML CODE: <input type="text" id="comboBox" placeholder="Search.." /> < ...

Refresh the navigation bar on vuejs post-login

Creating a client login using Vue has been a challenge for me. My main component includes the navigation bar and the content rendering component. The navigation component checks if the user is logged in to display the buttons for guests and hide the button ...

Overcoming Troublesome Login Input Box in Web

In an effort to streamline tasks in our office, I am working on automating certain processes. Specifically, this program is designed to log into our insurance company's website and extract information for payroll purposes. Below is the code snippet th ...

The property 'body' cannot be read because it is undefined

I have been attempting to incorporate passport logic into my controllers file, but I encountered an issue. When I place the logic inside the controllers, it gives me an error message saying "Cannot read property 'body' of undefined." However, whe ...

An error occurred while trying to convert a circular data structure to JSON during an API request within another

Attempting to make an API call within another API call in this code, however encountering the following error: Error: Converting circular structure to JSON const express = require('express'); const router = express.Router(); const config = requi ...

Implementing HTML page authentication with Identity ADFS URL through JavaScript

I have a basic HTML page that displays customer reports using a JavaScript function. The JavaScript makes an ajax call to retrieve the reports from a backend Spring REST API. In the Spring REST API, I have set up an endpoint "/api/saml" for authentication ...

Is there a method to incorporate a click event for the confirm button in the ElMessageBox UI element?

When I try to remove data from the table, I need a warning message to appear in the center of the screen first. The delete function is already set up, but I'm struggling to figure out how to implement a confirm button click event with ElMessageBox. I ...

Best Practices for Managing Data Across Multiple Locations in Angular.js

Currently, I am in the process of setting up a basic online shopping application using Angular.js. To display both an item list and item details, I utilize the ng-route module. For the item-list route, I employ resolve to load a JSON file containing vario ...

Steps to extract selected values from the MUI data grid

Can values be retrieved from a mui DataGrid? I have a table and I would like to create a custom export that takes into account user filters and the display status of columns. However, I need to access these filtered values. Is there a way to achieve this ...

Create a spectrum of vibrant colors depending on the numerical value

I'm attempting to create a function that generates rainbow colors based on a numerical value. var max = 10000; var min = 0; var val = 8890; function getColor(min, max, val) { // code to return color between red and black } Possible Colors: Re ...

Conceal a division on a webpage according to the URL of the specific

<script> function hideSearchField() { if (/menu/.test(window.location.href)) { document.getElementById('searchfield').style.display = 'none'; } } hideSearchField(); </script> I am trying to accomplish this using Jav ...

Setting character limits within textareas based on CSS classes in a dynamic manner

I'm looking to develop a JavaScript function that can set text limits for multiple textareas at once using a class, allowing for flexibility in case specific textareas need to be exempt. However, I'm facing issues with my debuggers - Visual Studi ...

Transmit XML data from controller to JavaScript

My goal on the UI is to display a formatted XML string when clicking on a link within a table of objects. I have tried passing the XML string to the View via a ViewModel and then setting it as a data attribute for the link. When clicked, JavaScript reads t ...

Issue with Angular Route Guard - Incorrect redirection to login page

I'm encountering an issue with my Angular app where even after the JWT token has expired, I am still able to navigate within the application without any API data being accessible. I've double-checked my setup and it seems right, but for some reas ...

Initially, when fetching data in React, it may return as 'undefined'

I have a function component in React that handles user login. The functionality is such that, based on the username and password entered by the user in the input fields, if the API response is true, it redirects to another page; otherwise, it remains on th ...

When working with express.js, the following error may occur: Uncaught Error [ERR_HTTP_HEADERS_SENT]: Unable to modify headers after they have been sent to the client

Seeking assistance for resolving this issue. The purpose of this code is: Update the artist using the specified artist ID and data from the request body, then save it to the database. Return a 200 response with the updated artist in the response body. If ...

Javascript malfunctioning - exhausted all troubleshooting options

My JavaScript code consists of a single line, but I keep encountering the "getElementById null" error. document.getElementById("menu-background").style.left = "0"; HTML: <html> <head> <title></title> <link rel="style ...

Is the new Angular 2 CLI tool incorporating Systemjs?

Seeking Answers Curious about the absence of systemjs.config.js file when using the new Angular2 CLI setup tool. Is there a way to install a basic version of Angular 2 without relying on the CLI tool available on angular.io? Past Experience In the past, ...