Variations in output observed from angular function across various sections within DOM

After fetching a list of permissions in the background, my goal is to display a page or an error message based on whether the user has the required permissions.

I encountered an unusual issue where both sections of the page are being displayed despite having one section with ng-show matching the permission function and another with the negated function. When I changed them both to use just the "isPermissioned" function, only the top one showed up while the bottom did not. It seems like they are receiving different values from the same function. Could this be due to the ordering of execution, causing one section to update before the other? Since I am binding to a function and not a variable, how can I ensure that the functions re-evaluate when there are changes?

The HTML code snippet is:

<div ng-controller="SEFlexHomeController" ng-show="isPermissioned">
    <!-- Tab functionality here -->
</div>
<div ng-show="!isPermissioned">
    <h3>You do not have the necessary permissions to view Secure Environment pages.</h3>
</div>

The JavaScript code is:

app.controller("SEFlexHomeController", ["$scope", "$http", "$modal", "$log", "$element", "$rootScope", "AlertsService", "AuthService", "SEApplicationService", function ($scope, $http, $modal, $log, $element, $rootScope, AlertsService, AuthService, SEApplicationService) {
        $rootScope.closeAlert = AlertsService.closeAlert;
        $scope.isDataLoading = false;
        $scope.AuthService = AuthService;
        
        // Function to determine if user is permissioned
        $scope.isPermissioned = function() {
            return AuthService.canAdministerFlex || AuthService.canViewFlexModels || AuthService.canRunFlexJobs || AuthService.canRunHighPriorityFlexJobs;
        }
    }
]);

The Auth service code is:

function AuthService($log, $http) {

    var authService = {
        // Boolean flags for different types of permissions
        canRunFlexJobs: false,
        canRunHighPriorityFlexJobs: false,
        canViewFlexModels: false,
        canApproveFlexModels: false,
        canAdministerFlex: false
    };

    // Fetch user claims and update permission flags
    authService.getUserClaims = function () {
        $http.post("/Admin/Auth/GetUserClaims")
            .success(function (response, status, headers, config) {
                if (response) {
                    angular.forEach(response.data, function (item) {
                        // Update permission flags based on user roles
                        if (item.Value === "SEFlexJobRunner")
                            authService.canRunFlexJobs = true;
                        if (item.Value === "SEFlexHighPriorityJobRunner")
                            authService.canRunHighPriorityFlexJobs = true;
                        if (item.Value === "SEFlexModelViewer")
                            authService.canViewFlexModels = true;
                        if (item.Value === "SEFlexModelApprover")
                            authService.canApproveFlexModels = true;
                        if (item.Value === "SEFlexAdministrator")
                            authService.canAdministerFlex = true;
                    });
                }
            })
            .error(function (reason, status, headers, config) {
                console.log(reason);
            });

    }
    // Call method to fetch user claims
    authService.getUserClaims();
    return authService;
};

Answer №1

When dealing with a function, remember to actually call it. Right now, you are passing the function itself to the ng-show directive, rather than its result.

<div ng-controller="SEFlexHomeController" ng-show="isPermissioned()">
    <div class="row" id="TabsSet1">
        <div class="col-md-12">
            <ul>
                <li ng-show="AuthService.canRunFlexJobs || AuthService.canRunHighPriorityFlexJobs"><a href="#tabs-Jobs">Jobs</a></li>
                <li ng-show="AuthService.canViewFlexModels"><a href="#tabs-Models">Models</a></li>
                <li ng-show="AuthService.canAdministerFlex"><a href="#tabs-Administration">Administration</a></li>
            </ul>
            <div id="tabs-Jobs" ng-show="AuthService.canRunFlexJobs || AuthService.canRunHighPriorityFlexJobs">
                <h1>Welcome to this jobs tab</h1>
            </div>
            <div id="tabs-Models" ng-show="AuthService.canViewFlexModels">
                <h1>Welcome to this models tab</h1>
            </div>
            <div id="tabs-Administration" ng-show="AuthService.canAdministerFlex">
                <h1>Welcome to this administration tab</h1>
            </div>
        </div>
    </div>
</div>
<div ng-show="!isPermissioned()">
    <h3>You have no permissions to view Secure Environment pages</h3>
</div>

Instead of using ng-show="!isPermissioned()", consider utilizing ng-hide like this: ng-hide="isPermissioned()"

UPDATE:

Also, it appears that your controller attribute should wrap both <div>s:

<div ng-controller="SEFlexHomeController">
    <div ng-show="isPermissioned">
        ...
    </div>
    <div ng-hide="isPermissioned">
        <h3>You have no permissions to view Secure Environment pages</h3>
    </div>
</div>

Answer №2

To prevent the creation of global variable references, it is advisable to include all module registering within an Immediately Executing Function.

Here's a simple example:

(function(){
//Insert your Angular code here (e.g. service or module)
}());

Answer №3

To properly display the content, make sure to execute the isPermissioned function by calling it. This will update the ng-show conditions as follows: ng-show="!isPermissioned()" and ng-show="isPermissioned" should be replaced with ng-show="!isPermissioned()" and ng-show="isPermissioned()" respectively.

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

Is there a way to store div content in a PHP Session?

Just starting to learn php & ajax, so be patient with me. I have a clickable map. When the user clicks on a point, the value is displayed in a div. Once they select a point, they should be able to proceed to the next step. Now I want to save the content ...

How to Generate an Array of JSON Objects in JavaScript on a Razor Page using a Custom ViewModel in MVC?

Attempting to populate the array within my script for future charting with D3.JS, I came across some issues. Following advice from this post, I used a specific syntax that unfortunately resulted in an error stating "Uncaught ReferenceError: WebSite is not ...

The addition of input fields on keyup creates problems in the initial field of each row

I am currently working with a table and attempting to calculate the sums as follows: td(1) + td(2) + td(3) = td(4), td(5) + td(6) + td(7) = td(8), td(9) + td(10) + td(11) = td(12). This is the code I have implemented: $(document).ready(function () { ...

The HTML checkbox remains unchanged even after the form is submitted

On a button click, I have a form that shows and hides when the close button is clicked. Inside the form, there is an HTML checkbox. When I check the checkbox, then close the form and reopen it by clicking the button again, the checkbox remains checked, whi ...

Is there a way to determine if an element has been scrolled past?

I am currently working on a script to detect when a specific element comes into view while scrolling. const targetElement = document.getElementById('sidebar'); window.addEventListener('scroll', () => { if (window.scrollY > tar ...

Incorporate a unique attribute into a select tag using Javascript

My goal is to dynamically generate a select element using JavaScript and include a custom attribute called data-placeholder. Is there a way to add non-standard attributes using JavaScript without triggering a browser error like: Uncaught referenceError: ...

What could be causing my search function to not recognize special characters?

It seems like there might be an issue with character encoding. My JavaScript search function is unable to identify specific strings that contain certain special characters such as parentheses, asterisks, and numbers. The JavaScript code I am using is quit ...

Utilizing App Script for Filtering Data with Multiple Criteria

Having trouble transferring data from a data sheet to my report sheet using multiple criteria for matching. I wrote some code that worked, but it's returning all data instead of filtering by criteria. I want the function to search for column criteria ...

Tips for parsing form values using jQuery AJAX:

Is there a way to extract form values and check if 15 objects have values or not? I attempted to do this using jQuery.parseJSON() but it didn't work as expected. [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Obj ...

Ways to deselect checkboxes with Typescript and Jquery

I have a set of checkboxes all labeled with the same 'types' class. There is a button on my webpage that should be able to toggle between selecting and deselecting all the checkboxes in this group. When checking the boxes, I use the following sc ...

Vue: event triggers malfunctioning and components unresponsive

I am new to Vue.js and I'm attempting to trigger an event from my grand-child component (card) to the child component (hand) and then to the parent component (main): card (emit play event) => hand (listen for play event and emit card-play event) ...

Express: adding a question mark to the URL when submitting the form

Upon submitting a form with a "?" in the URL, I noticed that when posting it redirects me to the page and still returns a "?" in the URL. Directory: server.js, index.html, package.json, package-lock, src/models/form.js server.js: const express = require( ...

Unexpected error encountered in Angular 2 beta: IE 10 displays 'Potentially unhandled rejection [3] SyntaxError: Expected'

Question regarding Angular 2 Beta: I am starting off with a general overview in the hopes that this issue is already recognized, and I simply overlooked something during my research. Initially, when Angular 2 Beta.0 was released, I managed to run a basic m ...

ways to assign the total of string array elements to the $scope variable

I've been working on binding the total sum of selected checkboxes within a table. I'm almost there, but something isn't quite right. The image above shows 2 checkboxes selected. https://i.sstatic.net/70af2.jpg The code snippet below showcas ...

Step-by-step guide on permanently updating the text of select options with JavaScript

Here is the code for a select option with different values: <select id="test" onchange="changeContent()"> <option>1</option> <option>2</option> <option>3</option> </select> The javascript function that chan ...

The set for generating dgeni documents is not currently specified

I am facing issues with the dgeni document generation tool where I encounter an error stating that 'Set is not defined', which leads me to believe the error is related to this issue. I have installed dgeni using npm install on both Windows 7 and ...

Verify WTForm after dynamic updates to select field options with Jquery

As I work on developing a flask application, I have successfully created a form using WTForms. This form consists of two SelectFields (dropdowns) and a submit button. My goal is to make the dropdowns dynamic - meaning that when the user selects an option f ...

Combining and restructuring multidimensional arrays in Javascript: A step-by-step guide

I'm struggling with transforming a multidimensional array in JavaScript. Here is an example of the input array: [ [['a',1],['b',2],['c',3]], [['a',4],['d',2],['c',3],['x',5]], [[&a ...

Showcase text in a straight row by utilizing ng-repeat and bootstrap

My goal is to show each word on a new line, similar to how words are displayed in a hangman game. The words should be displayed as blanks. <body ng-init="models = [['H','a','p','p','y'],['X',& ...

Unlocking the power of setting global variables and functions in JavaScript

Within my language.js file, the following functions are defined: function setCookie(cookie) { var Days = 30; //this cookie will expire in 30 days var exp = new Date(); exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000); document.cookie = coo ...