Using the Permissions directive in Angular

Currently, I am developing a Single Page Application (SPA) that interacts with a REST server on the backend.

The objective is to create a user interface that is consistent across all roles.

For example: On a product page, a guest can view the product and comments, a registered user can comment using a text box. An administrator has the ability to edit both comments and the product itself, all within the same SPA view.

Essentially, there are DOM elements that should be displayed for some users but not others.

To manage access control in my application, I have implemented a factory that checks if the user has the necessary privileges to access certain pages. This factory also updates the rootScope with the user's access level.

Within the compile function of the xLimitAccess directive, I validate the current user's access level to determine whether they can view the content within the directive before removing it.

Issue: The challenge lies in accessing the $rootScope from the compile function as it does not exist yet. If attempted in the link function, it is already too late to remove the element from the DOM.

Below is an example of HTML code:

<div class="product">...</div>

<div class="manageProduct" x-limit-access x-access-level="admin">...</div>

<div class="comment" x-limit-access x-access-level="user, admin">...</div>

<div class="comment" x-limit-access x-access-level="admin">...</div>

Javascript code snippet:

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

app.config(function($routeProvider){

    $routeProvider.
    when('/', 
        {
            templateUrl: 'views/home.html', 
            controller: 'homeCtrl',
            resolve: {auth : 'authUser'} //This page is only accessible to logged-in users
        }).
    when('/login', 
        {
            templateUrl: 'views/login.html', 
            controller: 'loginCtrl',
            resolve: {}
        }).
    when('/logout', 
        {
            templateUrl: 'views/logout.html',
            controller: 'logoutCtrl',
            resolve: {auth : 'authUser'} //This page is only accessible to logged-in users

        }).
    when('/register', 
        {
            templateUrl: 'views/register.html',
            controller: 'registerController',
            resolve: {}
        }).
    when('/admin', 
        {
            templateUrl: 'views/admin/home.html',
            controller: 'registerController',
            resolve: {auth: 'authAdmin'}
        }).
    otherwise({ redirectTo: '/'});
}).
run(function($rootScope, $location, $http, authUser){
    $rootScope.$on("$routeChangeError", function(event, current, previous, rejection){
        if(rejection.status == 401)
            $location.path('/login');
    })

    $http.get('/users/me', {withCredentials: true}).
    success(function(data, status, headers, config){
        $rootScope.roles = data.roles;
    }).
    error(function(data, status, headers, config){
    });
});

app.factory('authUser', function($http){
        return $http.head('/users/me', {withCredentials: true});
});

app.directive('xLimitAccess', function(){
    return{
        restrict: 'A',
        prioriry: 100000,
        scope: {
            xAccessLevel: '='
        }
        compile: function(element,$rootScope){//this is essentially the problem
            if(scope.xAccessLevel != $rootScope.roles)
                element.children().remove();
                elemnet.remove();
        }
    }
})

Answer №1

If you're facing the issue of not having access to $rootScope in your directive's compile function, one workaround is to inject it into your directive instead of directly into the compile function. You can achieve this by defining your directive like so:

app.directive('xLimitAccess', function ($rootScope) { }
. Keep in mind that the compile function does not support injection as it receives a predefined set of values directly.

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

Stop the entire page from scrolling when scrolling within a specific div element

I am looking for a solution to prevent the page from scrolling back to the previous section while scrolling within a specific div element. Currently, I am using Alvarotrigo's fullpage scroll plugin, although I am not sure if that is relevant to the is ...

JavaScript "alternating pattern"

When faced with this code test question, I decided to tackle it with the following approach: function createPattern(){ var result = '' for (var row = 0; row < 10; row++){ for (var col = 0; col < 10; col++){ ...

The value of the AngularJs controller remains static even after the factory's resolve

Currently, I am in the process of constructing a user page that displays essential information such as main data, details, and address. However, upon the initial load, this information fails to appear on the screen until I navigate away from the page and t ...

Implementing the expand and collapse functionality to the Discovery sidebar on the DSpace 4.2 xmlui platform

I recently began using DSpace and I am attempting to implement an expand/collapse feature in the Discovery sidebar of DSpace 4.2 xmlui using the Mirage theme. After finding some helpful jquery code, I attempted to add this functionality by placing the js f ...

What methods can I use to display or conceal certain content based on the user's location?

I'm looking to display specific content exclusively to local users. While there are APIs available for this purpose, I'm not sure how to implement them. I'm interested in creating a feature similar to Google Ads, where ads are tailored base ...

Adding a custom validation function to the joi.any() method - the easy way!

Is there a way to enhance joi.any() with a new rule that can be applied to any existing type, such as joi.boolean() or joi.string()? I already know how to extend joi by creating a custom type but that doesn't allow me to combine the new type with exis ...

Challenges with xmlHttpRequest in a search autocomplete feature similar to Google's suggestion feature

I am currently working on implementing an autosuggestion search field that functions similarly to Google Suggestion. I am utilizing pure JavaScript/AJAX along with two files: index.php and ajax-submit.php (which is responsible for querying the database). H ...

Implementing various event listeners for asynchronous JavaScript and XML requests (

Struggling to iterate through an ajax query and encountering a problem where the i value always defaults to 1. I'm not very well-versed in js so any suggestions on how to tackle this issue or possibly a better approach would be greatly appreciated. Th ...

Is there a way to set a fixed value for properties in Three.js?

I am on the hunt for the equivalent in Three.js to vertexAttrib. My goal is to assign a fixed value to my shader attribute. ...

Exploring the equality of objects in NodeJS

Currently, we are in the process of creating tests for a program. Our goal is to develop a functional test that validates whether the output of the program aligns with certain expectations. The data returned from the program consists of a complex JavaScrip ...

Having trouble navigating back to the homepage

Recently, I started following a tutorial on YouTube to create a basic frontend in React with Bootstrap. However, I encountered a roadblock while trying to implement a specific functionality. The issue stemmed from the fact that react-router-dom v6 no lon ...

Incorporating JSTree Into Your Website's Heading: A Step-By-Step

I'm in search of a way to integrate the following code snippet as a JSTree into the heading section of a webpage, depicted below: <div id="jstree"> <ul> <li>Core 1 <ul> & ...

Leveraging the power of the map function to cycle through two arrays

Right now in React, I am utilizing array.map(function(text,index){}) to loop through an array. But, how can I iterate through two arrays simultaneously using map? UPDATE var sentenceList = sentences.map(function(text,index){ return <ListGr ...

An issue with Azure App Service causing extra slashes in URLs

I am currently developing a node.js application that is being deployed on Azure App Service. On my local machine, the application functions perfectly at: http://localhost:55231/search?q=pink+floyd However, when deployed on Azure, the URL behaves strange ...

Having trouble locating the name WebGLObject in my TypeScript code

Every time I try to run ng serve command An error pops up on my screen saying: "WebGLObject cannot be found." ...

When hovering over certain transitioning elements in a D3JS chart, the animation execution is paused if other elements are also in the process of transitioning

Currently, I have been designing a horizontal bar chart and experimenting with transitions on various elements like rect and circle. The transitions are applied to attributes like width and r to achieve the desired effect. Everything seems to be working fi ...

The JSON syntax contains an unexpected token

I am encountering an issue with a JavaScript variable named "text" that contains the following value: text={"text":"@RT #Olle_Carly Nuevas filtraciones del iPhone 6: así sería comparado con el Samsung Galaxy S5 y el iPhone 5S: Des... http://t.co/eRuXLS6 ...

How can I modify the date format using the Google Ajax Feed API?

Currently, I am utilizing Google's AJAX Feed API to pull data from an RSS feed. However, I am curious about how to modify the date format. The current format fed by "datePublished" appears as follows: Sun, 29 Jan 2012 23:37:38 -0800 Is there a way t ...

href not functioning properly on subsequent clicks, whereas onclick remains active

I'm experiencing an issue with a button that opens a modal. When clicking the button, it's supposed to open a new page in the modal and also make an API call for processing before loading the new page. <a class="btn btn-primary" type='b ...

Showcasing interactive column titles by employing angularjs in an html table

After preparing my data, I aim to showcase it in an HTML table. However, a complication arises each time the $http service is called as it returns a varying number of columns (n). Essentially, I wish to have the first row of the data serve as column names, ...