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

Unit testing in AngularJS involves the process of attaching data from the $q.resolve() function to an object

I am currently evaluating a service that relies on another service for API calls, which I refer to as the data service. The data service has already been tested separately, so I have created a basic implementation with placeholder functions; data is then r ...

Converting Background Images from html styling to Next.js

<div className="readyContent" style="background-image: url(assets/images/banner/banner-new.png);"> <div className="row w-100 align-items-center"> <div className="col-md-7 dFlex-center"> ...

Exploring the possibilities of page manipulation using React Native WebView

I'm encountering an issue with my implementation of react-native-webview. When I use it to open a webpage, the audio doesn't start playing automatically. Instead, I have to press a button for it to play. Is there a way to make the audio play dire ...

Encountering issues with Office.context.document.getFileAsync function

I am experiencing a strange issue where, on the third attempt to extract a word document as a compressed file for processing in my MS Word Task Pane MVC app, it crashes. Here is the snippet of code: Office.context.document.getFileAsync(Office.FileType.Co ...

Remove background image when input form field is in focus

I am currently experimenting with the following approach: $('input').on('click focusin', function() { $('.required').hide(); }); However, it appears that this logic is not functioning as intended. Here is an ...

Show a loading image after clicking on an image or button using JavaScript

I recently created an App using PhoneGap and JqueryMobile. Transitioning between multiple HTML pages by clicking on images seems to be causing slow loading times, leaving end users unaware of what's happening in the background. I am looking for a way ...

NPM packages installed on a global level are not being detected

Recently, I experienced a system crash that led me to delete some files in an attempt to fix the issue. Among those files may have been ~/.profile. Since restoring my system, I've noticed that my globally installed npm packages are no longer functioni ...

What is the best method for checking for JavaScript errors when using Selenium WebDriver in conjunction with NodeJS?

When it comes to coding in JavaScript, not Java, my focus is on running a specific website like foo.com. I typically set it up as follows: var webdriver = require("selenium-webdriver"); By = webdriver.By, until = webdriver.until; var chrome = req ...

JavaScript date input formatting with HTML

When using the input date picker in HTML, the default format displayed is MM-DD-YYYY. <input type="date" id="gdatum" /> Is there any method to change the mask to DD-MM-YYYY? ...

When submitting data through jQuery.ajax that includes the string "???", the value is transformed into "jQuery19107363727174233645_1373301489648?"

Server side script: var configuration = {"NumberOfCPUs":"2","NumberOfCores":"4","OSType":"Linux","OSVersion":"???"}; var identifier = 0; var responseReceived = false; //sending data to the server: $.ajax( { ...

send the variable to the deferred done function

Having trouble passing a variable into a done callback. var getDataForCompany = function(company_id) { $.ajax({ type: "post", url: url, data:{ company_id: company_id } }).done(function(returnedData, textStatus, j ...

Display/Conceal Dropdown Menu for Combobox Using only Javascript

In my asp.net user control, I am generating markup that looks like this: <div id="combobox1"> <div id="combobox1_text"><span>combobox 1</span></div> <div id="combobox1_ddl"> <input type="checkbox" id="combobo ...

Tips for sending Json data through a form to a controller and storing it in a database

I am working on a form that contains a sample table with values. The table (id=sampleTbl) has two columns: name and age. My goal is to save this data into my database table named person (id=AI, name, age) when the submitButton (id=idOfButton) is clicked. ...

Vue 3 Option api: Issue with v-model input not propagating from child component to parent element

I am currently working on a new project using Nuxt 3, and I have encountered an issue with a contact form where the input values from a child component are not being received by the parent element. Let's dive into the code breakdown: Parent Component ...

Utilize node.js on your local machine and leverage gulp to monitor any modifications

I recently copied a repository from https://github.com/willianjusten/bootstrap-boilerplate and followed these steps. git clone git://github.com/willianjusten/bootstrap-boilerplate.git new_project cd bootstrap-boilerplate npm install gulp The gulp comman ...

Submit image and transfer it to server using AngularJS and Jersey

I need help with my form that contains the following fields: <div class="form-group"> <label>Username</label> <input type="text" ng-model="username" class="form-control"> </div> <div class="from-group"> < ...

Getting the most out of the fastest-validator package: Implementing multiple patterns and custom messages

Utilizing the powerful fastest-validator library for validation purposes. I have a requirement where the password field must contain at least one character and one number. Along with this, I am in need of specific messages for validating these conditions ...

Is it possible to utilize EmberJS or other frameworks without the necessity of setting up its server?

I am in search of a JavaScript framework that offers the following features: MV* Well-structured HTML file as template Fast rendering (possibly using virtual DOM) Ability to combine and be compatible with other plugins or libraries Edit on tablet IDE app ...

Is there a way to eliminate spaces from a string using react-native?

As a user of react-native, I've encountered an issue with inconsistent line breaks when inputting long strings on the screen. For example: I aim to achieve consistent string wrapping as shown in the image below: Here is my code. How can I address t ...

What is the best way to pass a JSON object from R to Plumber in a format that JavaScript can interpret as an array instead of

My goal is to receive a JSON raw response from R Plumber and then utilize it in Angular. However, I am encountering an issue where the JavaScript Framework is interpreting it as a string instead of recognizing it as JSON format. "[{\"id&bsol ...