Creating a dynamic sidebar based on roles in AngularJS

I'm looking to create a dynamic sidebar based on the user's role, which is stored in $rootScope.login. However, I'm unsure of how to integrate it into template.js.

Below is my JavaScript code and I'm still relatively new to AngularJS.

template.js

$templateCache.put('template/sidebar-left.html',
        "<div class=\"sidebar-inner c-overflow\"><div class=\"profile-menu\"><a href=\"\" toggle-submenu><div class=\"profile-pic\"><img src=\"img/profile-pics/1.jpg\" alt=\"\"></div><div class=\"profile-info\">Malinda Hollaway <i class=\"zmdi zmdi-caret-down\"></i></div></a><ul class=\"main-menu\"><li><a data-ui-sref=\"pages.profile.profile-about\" data-ng-click=\"mactrl.sidebarStat($event)\"><i class=\"zmdi zmdi-account\"></i> View Profile</a></li><li><a href=\"\"><i class=\"zmdi zmdi-input-antenna\"></i> Privacy Settings</a></li><li><a href=\"\"><i class=\"zmdi zmdi-settings\"></i> Settings</a></li><li><a href=\"\"><i class=\"zmdi zmdi-time-restore\"></i> Logout</a></li></ul></div><ul class=\"main-menu\"><li data-ui-sref-active=\"active\"><a data-ui-sref=\"home\" data-ng-click=\"mactrl.sidebarStat($event)\"><i class=\"zmdi zmdi-home\"></i> Dashboard</a></li><li data-ui-sref-active=\"active\"><a data-ui-sref=\"timeline\" data-ng-click=\"mactrl.sidebarStat($event)\"><i class=\"zmdi zmdi-layers\"></i>Timeline</a></li>...");

controller.js

this.loginF = function(user) {

    $http.post("data/login.php", user).then(function(userData) {

        $rootScope.login = userData.data
        if( $rootScope.login == "failed" ) {
            alert(JSON.stringify($rootScope.login))
        } else {
            window.location.assign("home.html");
        }
    })
} 

Answer №1

To implement this functionality, consider creating a directive like the following:

app.directive("userMenu", function() {
    return {
        restrict: "AE",
        scope: {
            user: "="
        },
        templateUrl: "template/sidebar-left.html",
        link: function($scope, $elem, $attrs) {
            $scope.hasRole = function(role) {
                if (!$scope.user) {
                    return false;
                }

                // If the user data model is like { roles: ["admin", "editor"] }
                return $scope.user.roles.indexOf(role) > -1;
            }
        }
    }
});

You can then use this directive in your sidebar-left template as shown below:

<div>
    <ul class="menu">
        <li ng-if="hasRole('admin')">
            <a href="#">This will only be displayed if the user has the 'admin' role</a>
        </li>
        <li>
            <a href="#">This will always show, regardless of the user's role</a>
        </li>
    </ul>
</div>

Finally, include it in your HTML markup like this:

<div user-menu user="$root.login"></div>

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

Steps for showcasing each element of an array separately upon a mouse click

I am working on a website where each click on the screen reveals a new paragraph gradually. I plan to organize these paragraphs in an array and display them one after the other in sequential order upon user interaction. The challenge lies in combining thes ...

What occurs when you use the statement "import someModuleName from someModule" in JavaScript?

When reusing a module in multiple places, you typically use module.exports = yourModuleClassName to make the module exportable. Then, when you want to use it elsewhere, you can simply import it with import yourModuleClassName from 'yourmodulePath&apos ...

Seamless Exploration with Google StreetView

Google uses a special effect on StreetView images to transition smoothly between them. You can see an example of this effect in the images below, with the second image showing it being applied. My question is: How can I incorporate this same effect into m ...

Aligning container divs at the center in various screen resolutions

I recently constructed a portfolio website using Bootstrap and Isotope JS. In my layout, I have a container div which works perfectly when viewed on a desktop browser - displaying 3 divs in one line. However, the issue arises when the resolution changes an ...

My controller is playing hide and seek with Ionic and it seems

I have been working on integrating a side menu into my app, which required me to make changes to how the controllers are set up. I introduced a menu controller, but now I keep encountering this error message: Argument 'MenuCtrl' is not a functio ...

Issue: It seems like there is an error with using functions as a React child. Uncertain about the exact location

This specific issue is one of the two errors I have come across in the same application referenced in my previous inquiry. The first error encountered is as follows: Warning: Functions are not valid as a React child. This may occur if you mistakenly return ...

What is causing my cookie script to malfunction?

I'm experiencing an issue with my cookie script on the following website: Upon visiting my site, you'll come across a hidden <div id="popupDiv"> Due to the display: none property in the CSS, it's not visible as intended. However, it ...

The Mantine date picker is causing an error stating that objects are not valid as a React child

I'm currently experimenting with utilizing Mantine Date in NextJS. The goal is to have the selected date displayed in the HTML text heading when a user clicks on it. For instance, if a user selects January 1st, 2023, the text should show like this: Da ...

I am looking to upload an image to the database using ajax or any alternative method

I need assistance in uploading an image to a Spring Boot backend via AJAX or any other method. Below is the img tag and form I have implemented, along with an AJAX request to send form data. How can I include the image in this process? AJAX request (exclu ...

The Express JS application fails to validate the authentication token provided by Angular

I am currently working on an API that functions as an Express JS application, and I am utilizing Angular JS to send requests to this API. The API mandates authorization to be sent in the header, and I am facing challenges accomplishing this in Angular. H ...

Using Typescript to create an asynchronous function without explicitly declaring a Promise

When you examine TypeScript's async function, you may notice the redundancy with "async" and "Promise<type>". public async test(): Promise<string> { return "Test"; } Is there a way to configure TypeScript to handle async types ...

Dealing with multiple parameters within the app.param() function

Currently, I am developing an API using Express.js and facing a challenge in implementing an app.param() function for handling the id parameter in a GET request: app.param('id', (req, res, next, id) => { const envelopeIndex = Number(id); ...

Testing the unit with a customized header in the interceptor

I've been struggling to execute a unit test within an Angular 6 interceptor, but despite numerous attempts, I keep encountering the following error: Error: Expected one matching request for criteria "Match by function: ", found none. I'm rela ...

Focusing on particular jQuery elements that share the same class names

I am facing an issue with dynamically generated divs that share the same class names. When I hover over the parent div (myDiv), I want to trigger an event and add a class to the myDiv child button. However, when I click on the parent div, I want to unbind ...

Give it a little time before uploading a widget onto the page

As a newcomer to programming, I recently came across this code from an open source project. I am in the process of loading a widget onto a website. Instead of having the widget load instantly, I would like it to wait 10 seconds before displaying. Below i ...

Ways to implement the React.FC<props> type with flexibility for children as either a React node or a function

I'm working on a sample component that has specific requirements. import React, { FC, ReactNode, useMemo } from "react"; import PropTypes from "prop-types"; type Props = { children: ((x: number) => ReactNode) | ReactNode; }; const Comp: FC< ...

Exploring VueJS Router History Mode with NGinx web server

After conducting research, I discovered several issues similar to the one I am facing. Currently, I have a docker-compose setup on Digital Ocean with NGinx, VueJS, and a Static Landing Page. Everything was working fine until I added a new route with a fo ...

Make the current tab the active tab with the help of AngularJS

I have a set of five tabs that are functioning correctly. However, when I refresh the page, the active tab reverts back to its default state instead of staying in its current active state. Can anyone help me identify where I may be making a mistake? Here ...

Guide: Linking RCTCameraRoll to Android

I am currently attempting to utilize the CameraRoll library, however, I have encountered an obstacle. The documentation does not provide instructions on linking it for Android. It only offers guidance on how to link it for iOS. While it does mention that ...

Advantages and Disadvantages of Implementing Ajax for Form Validation

Exploring the benefits of validating forms with Ajax, I find it to be a valuable tool in preventing code redundancy. However, before making the switch, I am curious about any potential drawbacks compared to traditional JavaScript validation. While I have c ...