Developing a dynamic user interface using an Angular framework and populating it with

I am currently learning Angular (version 1) and facing an issue with my layout. I need to dynamically change the navigation based on the type of user that is logged in. To achieve this, I make an API request when the page loads to fetch the user object data, which will be shared with other controllers on the page.

Here is my DashboardController:

app.controller('DashboardController', function($scope, UserService, $rootScope){
        $scope.loading = true;

        if($scope.loading) {
            $scope.doInitialisation
        }

        $scope.isSuper = function() {
            if($scope.user.isSuper == 1) {
                return true;
            }

            return false;
        }

        UserService.authenticatedUser()
            .then(function(response){
                $scope.loading = false;
                $rootScope.user = response.message;
            }, function(error) {
                $scope.hasError = true;
                $scope.errors = error.message;
            });
    });

In my template, I'm attempting to display a UL element based on the user type:

<ul ng-if="isSuper()" ng-include="dashboard/nav/super.html" id="sidebar-menu" class="sf-js-enabled sf-arrows">

</ul><!-- #sidebar-menu -->

However, I encounter the following error:

Cannot read property 'isSuper' of undefined

I suspect this error occurs because isSuper() is fired before my AJAX request has completed loading. Is there a way to resolve this? Can I move the logic from the template to the AJAX success callback?

Any suggestions for a more efficient approach?

Answer №1

The following code snippet illustrates how Angular updates the view asynchronously when data arrives, using data binding to display HTML elements with the ng-if directive. Check out this Plunker for an example of using the ng-include directive.

angular
  .module('demo', [])
  .controller('DefaultController', DefaultController);

DefaultController.$inject = ['$timeout'];

function DefaultController($timeout) {
  var vm = this;
  vm.user = {};

  $timeout(function() {
    vm.user.role = 'admin';
  }, 1000);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo">
  <div ng-controller="DefaultController as vm">
    <div ng-if="vm.user.role === 'admin'">
      <span>Hello, Admin</span>
    </div>
  </div>
</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

React Big Calendar encountered an error: The element type provided is not valid, as it is expected to be a string for built-in

Error One: The element type is invalid: it was expecting a string (for built-in components) or a class/function (for composite components), but received undefined. This could be due to not exporting your component correctly from the file where it's d ...

How to resolve a TypeError saying "Object(...) is not a function"?

I've been attempting to display material-ui tabs as a component on another page, but I'm encountering an error that causes the code to break when loading the page with this component. I've tried two different methods of rendering this compo ...

Implementing Isotope layout in Reactjs with data-attributes for filtering and sorting content

I am currently working on optimizing the isotope handler within a react component. My goal is to implement filter options such as category[metal] or category[transition], as well as combo filters like category[metal, transition]. Here is the sandbox for t ...

How can I effectively hide the headMenu in a different controller?

I need assistance with hiding my headmenu in the application. app.controller("kpiOverviewCtrl", function ($scope, $stateParams,) { "use strict"; var setUpController = function () { $scope.headmenu = $state.current.controller === "kpiCompareCtr ...

Obtain a numerical output from a selection of numbers

I am facing a simple problem that I can't solve due to my lack of knowledge and have not been able to find any solution online. What I want to achieve is: Create a "value 1" from an array of integers. Generate a random "value 2". Check if the rando ...

Establishing the null values for input parameters

Whenever the button is clicked, I want to reset the input values to null. The function spremi() gets triggered when the button is clicked, but I want to set the values of podaci.tezina and podaci.mamac back to their initial values so that the user can en ...

Displaying just the initial ten items with AngularJS and dir-pagination-controls

<tr dir-paginate="plan in access |itemsPerPage: 10" total-items="planCount" current-page="current"> <td>{{plan._id}}</td> <td>{{plan.name}}</td> <td>{{plan.email}}</td> <td>{{plan.cont ...

Node.js AJAX post causing HTML page to not load properly

When using express.js, I want to be able to redirect to an HTML page after clicking on a table element. Currently, the output in the console.log is the HTML source instead of being redirected and interpreted as an HTML page. Here is my click function usin ...

Strategies for resolving duplicate jQuery code in my project

Trying to simplify my jQuery code that handles video selection and playback functionality. Users can click on a thumbnail or button to play a specific video, with the title of the video changing accordingly. Despite achieving the desired outcome, the cur ...

Tips for optimizing the page speed of your Pixi JS app by ensuring it runs efficiently after the page loads

On my website, I implemented a dynamic gradient animation with shape-changing blobs using pixi js. The animation functions flawlessly, but the issue arises when I run page speed tests - the test assumes that the page has not finished rendering because the ...

Intermittently play a series of sound files, with only the final sound ringing out

My goal is to create an app that plays a sound based on a number input. I have several short MP3 audio files for different numbers, and I want the app to play these sounds in sequence. However, when I try to do this, only the last sound corresponding to th ...

When organizing data, the key value pair automatically sorts information according to the specified key

I have created a key value pair in Angular. The key represents the questionId and the value is the baseQuestion. The baseQuestion value may be null. One issue I am facing is that after insertion, the key value pairs are automatically sorted in ascending ...

What makes fastify-plugin better than simply calling a regular function?

I recently came across a detailed explanation of how fastify-plugin operates and its functionality. Despite understanding the concept, I am left with a lingering question; what sets it apart from a standard function call without using the .register() metho ...

Trigger the execution of the second function upon the successful completion of the first

In the following code, my concept is to display: The clicked kingdom (clicked_id) initiates an attack on (clicked_id). https://i.stack.imgur.com/Bx8QW.png https://i.stack.imgur.com/Cg2GL.png https://i.stack.imgur.com/gUNxM.png How can I trigger the sec ...

What is the method for accessing the Redux store content directly in the console, without using any developer tools

By utilizing React Devtools, I am able to access the store by: $r.store.getState() Is there an alternate method to retrieve the store without using React Devtools? ...

"Experience the power of utilizing TypeScript with the seamless compatibility provided by the

I'm attempting to utilize jsymal.safeDump(somedata). So far, I've executed npm install --save-dev @types/js-yaml I've also configured my tsconfig file as: { "compilerOptions": { "types": [ "cypress" ...

What is the process for transferring an existing collection or data in Firestore to a subcollection?

My firestore database currently has the following structure with documents: root | |---transactions/... I am looking to transfer all transactions to a new subcollection as shown below: root | |---users/user/transactions/... Any suggestions on how I can a ...

Encountering memory leaks and displaying repetitive data due to having two distinct observables connected to the same Firestore

I am currently utilizing @angular/fire to retrieve data from firestore. I have two components - one serving as the parent and the other as the child. Both of these components are subscribing to different observables using async pipes, although they are bas ...

Optimal strategies for initializing Knockout JS models from backend code

Upon taking over a website that utilizes knockout js and asp.net, I noticed some performance issues during the initial page load. After investigating, I found that there are approximately 20 models on the site, each making an ajax call to retrieve data fro ...

How can I download a PDF file in React.js using TypeScript on Next.js?

I've created a component to download a PDF file. The PDF file is named resumeroshan.pdf and it's located inside the Assets folder. "use client"; import resume from "/../../Assets/resumeroshan.pdf"; export default function Abo ...