AngularJS Custom Navigation based on User Roles

I am currently developing a small web application using angular. My goal is to implement role-based navigation in the app. However, I am facing an issue where the isAdmin function does not seem to be getting called on page load, resulting in only the foo anchor tag being visible.

HTML

<body ng-controller='AccountController'>
    <nav class="navbar navbar-default">
      <ul>
          <li><a href='google.com'>foo</a></li>
          <li ng-if="isAdmin()"><a href='google.com'>bar</a></li>
      </ul>
    </nav>
</body>

AccountController

var app = angular.module('appControllers', []);

app.controller = angular.controller('AccountController', ['$scope', 
function($scope, $http) {
    $scope.isAdmin = function() {
        return true; //Just as a test to make sure it works
    }
}]);

My ultimate goal is for this functionality to hit a web service that will determine the administrator status, but for now, I just want to get it working.

Thank you in advance for all your assistance,

Andres

Answer №1

In the given scenario, it is suggested to eliminate the braces for the code to function correctly. However, a more efficient approach would be to implement a custom directive that ensures functionality. For instance:

<section class="custom-section" display-for-role="ROLE_A,ROLE_B"></section>

This method allows for better management of user roles and their corresponding permissions.

appModule.directive('managePermissions', ['someState', function (appState) {
  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      var currentUser = someState.getCurrentUser();
      scope.$watch(someState.watchCurrentUser, function(newVal, oldVal){
         if (newVal === oldVal){
           return;
         }
        toggleVisibility(element,attrs,newVal);
      });
      toggleVisibility(element,attrs,currentUser);
    }
  }

var toggleVisibility = function(element,attrs,user){
element.hide();
if (user) {
  var role = attrs.displayForRole;
  if (role){
    role.split(',').forEach(function(item){
      if (item === user.role){
        element.show();
      }
    })
  }
}};

Answer №2

To eliminate unnecessary parentheses after 'isAdmin', try revising your code like this:

function($scope, $http) {
    $scope.isAdmin = function() {
        return true; //This is just a test to ensure it functions correctly
    }
}

I hope this suggestion proves helpful...

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

Encountering an issue with core.js:15723 showing ERROR TypeError: Unable to access property 'toLowerCase' of an undefined value while using Angular 7

Below, I have provided my code which utilizes the lazyLoading Module. Please review my code and identify any errors. Currently facing TypeError: Cannot read property 'toLowerCase' of undefined in Angular 7. Model Class: export class C_data { ...

Uncovering the characteristics of a GeoJSON data layer within Google Maps V3

Is there a way to access the properties of the data layer itself when loading a geoJSON file into a Google Map? I understand how to access the individual properties like posts_here, but I'm interested in obtaining the properties for the layer as a wh ...

Error connecting Node.js, express, and socket.io application

My app is a simple one that utilizes the socket.io module for node.js. Everything runs smoothly when I start my server with the command node express_server.js. However, when I try to open my page at http://localhost:8080 in the browser, Node.js throws an e ...

Tips for refining a list to only include items that contain every element from a specified array

Is there a way to search for all elements in an array and display them if they are all present? For instance, consider the following: const data = [ { "languages": ["JavaScript"], "tools": ["React", "Sass"] }, { "languages": ["Python" ...

What is the best way to trigger a modal to appear when dynamically generated items are clicked?

My objective is to retrieve specific data from the server and present it in a list format on my webpage. The list displays correctly, but I want users to be able to view additional details for each list item by clicking on it, triggering a modal popup. How ...

Transforming an HTML file into a Vue.js component

I'm working on a login.vue file and I need to incorporate styling along with the necessary js and css files. Unfortunately, I'm clueless about how to achieve this within the login.vue file. Below is a snippet from the html file: <!DOCTYPE ht ...

What are the reasons for validation failure when it is moved into a method?

I am currently in the process of developing a validation function in JavaScript. However, when I extracted the logic into a private method, my validation started failing and I can't seem to figure out why. Here is my HTML definition: <input type= ...

Parse a string and generate an array using regular expressions in JavaScript/Node.js

I'm currently working on coding in JavaScript to extract an array of elements after splitting using a regular expression. var data = "ABCXYZ88"; var regexp = "([A-Z]{3})([A-Z]{3}d{2})"; console.log(data.split(regexp)); The current output is [ &a ...

Having trouble with Semantic UI Modal onShow / onVisible functionality?

Seeking assistance with resizing an embedded google map in a Semantic UI modal after it is shown. After numerous attempts, I have narrowed down the issue to receiving callbacks when the modal becomes visible. Unfortunately, the onShow or onVisible functio ...

Using TypeScript with React and Redux to create actions that return promises

Within my React application, I prefer to abstract the Redux implementation from the View logic by encapsulating it in its own package, which I refer to as the SDK package. From this SDK package, I export a set of React Hooks so that any client can easily u ...

Having trouble getting Angular-UI-Select to work with a basic variable on $scope?

How can you reset an array with selected values so that the values can be reselected from the dropdown? I am working with a people array where the values are initially displayed in a select dropdown. When I choose certain names, they get transferred to th ...

Executing all middleware within an express route

Currently, I am in the process of constructing an API using express and have implemented multiple middleware functions in my routes. One of the endpoints I am working on is displayed below: Router.route('/:id/documents') .get([isAuthenticated, ...

Displaying values dynamically as they transition between states in Reactjs

There are four components that I'm working with - UserHome, SearchFlight, Events, and Alerts. The UserHome component is where I import all the other components: <SearchFlight/> <Events /> <Alerts /> Within the SearchFlight compone ...

Persistent header remains visible while moving between pages in a single-page application

I'm having an issue with Datatables and AngularJS when using the FixedHeader plugin. Everything works perfectly when the table is visible on the page, but once I navigate to a different page within my single page application using angular UI router, t ...

Issue with sending functions to other components in Angular

I'm currently facing an issue with passing functions to other objects in Angular. Specifically, I've developed a function generateTile(coords) that fills a tile to be used by leaflet. This function is located within a method in the MapComponent. ...

Designing a web application with Angular2

As a newcomer to Angular2, I have recently started working on creating a simple hello world application. I have come across the concept of Modules and Components in Angular2. My main source of confusion lies in how to properly design an Angular2 applicat ...

Comparison: JavaScript Cookies vs PHP Cookies

I have been trying to implement the following code: JS: Cookies.set(post_id + '_' + user_ip, post_id + "_" + user_ip, { expires: 1 }); PHP: $cookie_str = $post_id.'_'.get_client_ip(); if (isset($_COOKIE[$cookie_str_]) ){ print_r ...

Can you clarify the semver meaning of the >= operator and what is the highest version it permits?

It's commonly known that when using symbols like ^, it represents anything up to the next major version, and ~ means only patches. However, there seems to be a lack of clarity regarding what the maximum version is when utilizing >=. So, how should ...

Transferring the data entered into an input field to a PHP script, in order to retrieve and display the value with JavaScript, unfortunately results in a

My situation involves a form that consists of only one input text field (search_term) and a submit button. The goal is to enter a keyword into the input field, click Submit, have the keyword sent to a php script for json encoding, and then returned back t ...

Logging in using email, phone number, or username on Node.js platform

How can I implement a login system in node.js and MongoDB that allows users to log in with their email, phone number, or username along with a password? Similar to the login functionality seen on Instagram, users should be able to enter their email or u ...