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 incorporating a JavaScript snippet from Google Trends into an HTML webpage

Hey everyone, I've been trying to incorporate a JavaScript script to display Google Trends on an HTML page. I copied the embed code directly from the first image at and modified it as follows. Unfortunately, it's not working as expected. <ht ...

How can I pass a DOM element as a prop in Vue 3?

As someone who is brand new to Vue, I'm exploring the possibilities. Although it's not something I typically do, I believe achieving a similar outcome in React + JSX (untested) could look like this: render() { const el = <p>Blah <a hre ...

When attempting to send coordinates to the Polyline component in React Native, an error is encountered stating that NSNumber cannot be converted to

Trying to pass coordinates from BackgroundGeolocation.getLocations() is causing an issue. Upon passing the coordinates, I encounter the following error message: JSON value '-122.02235491' of type NSNumber cannot be converted to NSDictionary I ha ...

`Can you provide guidance on implementing font-awesome icons on NativeScript?`

I can't seem to figure out how to incorporate font-awesome icons into my app that I'm developing with NativeScript. I've experimented with different methods, such as trying to include the unicode of the desired icon in the hint attribute li ...

Having trouble getting my Win and Lose Divs to display in my IF statement within the Card Game

Currently, I am developing a card game where players are presented with a card generated by the computer. The player has to decide whether the next card will be higher, lower, or equal to the current one by clicking corresponding buttons. if ((playerChoic ...

Tips on verifying the count with sequelize and generating a Boolean outcome if the count is greater than zero

I'm currently working with Nodejs and I have a query that retrieves a count. I need to check if the count > 0 in order to return true, otherwise false. However, I am facing difficulties handling this in Nodejs. Below is the code snippet I am strugg ...

Utilize ngModel in conjunction with the contenteditable attribute

I am trying to bind a model with a tag that has contenteditable=true However, it seems like ngModel only functions with input, textarea or select elements: https://docs.angularjs.org/api/ng/directive/ngModel This is why the following code does not work ...

Struggle encountered while incorporating PayPal into my project

Recently, I encountered an issue while trying to integrate the PayPal-node-SDK into my project for a Pay with PayPal option. The error message I received was: XMLHttpRequest cannot load https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&a ...

Tips for selecting checkboxes with fetched information

I have created a script that passes json data to a variable and then collects all the necessary information such as chapterid, questionid ...etc on the inner html page. jQuery Code: $('div[id^="questionsNo_"]').ready(function() { var assessme ...

What is the best way to deactivate unclicked href links within a loop?

Looking at the template image, my goal is to disable all links that were not clicked when one of the links from 'number1' to 'number3' is clicked. For example, if 'number2' is clicked, then 'number1' and 'number ...

Adjust size of item within grid component in VueJS

I have a grid container with cells and a draggable item in a Vue project. I am trying to figure out how to resize the box inside the grid component (refer to images). https://i.stack.imgur.com/q4MKZ.png This is my current grid setup, and I would like the ...

PHP is consistently failing to decode a JSON object generated by JavaScript, with the error code always being 4

In my JavaScript code, I am working on creating a map of key and value pairs. To achieve this, I create an object and store it in a hidden textarea. My intention is to retrieve the data using PHP, decode the object, and ultimately save it to a database. Th ...

Finding the index of an element in an array using the filter method in Angular JavaScript

As I was working with an array of pages in a book, I wanted to find the index of a specific page that had been identified using filter. While my current function gets the job done, I can't help but wonder if there's a way to combine indexOf or fi ...

What is the best way to access a value within a JSON object in a React render method?

Overview I am currently working on creating a blog using React and JSON data. Upon checking this.state.blogs, I am getting the output of: [object Object],[object Object],[object Object]. I have attempted to use the .map function but I am not sure how to ...

I built a custom Angular application integrated with Firebase, and I'm looking for a way to allow every user to have their individual table for managing tasks

I am looking to enhance my code so that each user who is logged in has their own tasks table, which they can update and delete. Additionally, I need guidance on how to hide menu items tasks, add-tasks, logout for users who are not logged in, and display th ...

Having trouble with the full-screen feature not functioning properly?

I am currently in the process of creating a custom video player and I need to include a full-screen button. However, when I click on it, the video does not expand to fill up the entire screen. I am using javascript, css3, and html5 for this project. Any as ...

Making modifications to the CSS within an embedded iframe webpage

Assigned with the task of implementing a specific method on a SharePoint 2013 site. Let's dive in. Situation: - Within a page on a SharePoint 2013 site, there is a "content editor" web part that displays a page from the same domain/site collection. T ...

Utilize dynamic CSS application within an Angular application

In my Angular application, I dynamically load URLs inside an iframe and want to apply custom.css to the loaded URL once it's inside the iframe. I attempted using ng-init with angular-css-injector function in the iframe, but the CSS is not being applie ...

Issue with Vue.js: routes are not found upon page refresh

Here is a basic vue-routing example: const Foo = { template: '<div>foo</div>' } const Bar = { template: '<div>bar</div>' } const routes = [ { path: '/foo', component: Foo }, { path: '/ba ...

Utilizing Angularjs and Symfony2 for Video Uploads

When incorporating AngularJS and Symfony2 with a MongoDB database, what is the optimal method for uploading videos? Is it more efficient to upload directly to the database or store them as application files? ...