Rendering template and data from a promise in AngularJS: A comprehensive guide

Hey there, I'm diving into the world of Angular and I've been struggling for the past couple of days trying to figure out a solution for this issue. Not entirely sure if my approach is right either.

My goal is to create a simple page with a dynamic menu. When a user clicks on a menu link, the corresponding view should load below the menu without refreshing the entire page. Sounds straightforward, right?

However, here's the catch - I need to have separate menus for admins and regular users, which are loaded through ajax. Here's a snippet of what I'm dealing with:

[
    {
        name: "Manage games",
        templateUrl: "/view/mygames.html",
        url: "/games",
    },
    {
        name: "Weekly Reports",
        templateUrl: "/view/myreports.html",
        url: "/reports"
    },
    {
        name: "Manage Users",
        templateUrl: "/view/users.html",
        url: "/users",
        adminRequired: true
    }
];

Once the menu is loaded, clicking on a menu item should trigger an ajax call to fetch data from the specified url, while the template to display this data will also be fetched via an ajax call to the templateUrl.

So, how can I achieve this? Essentially, I want to have a directive/component that starts off empty and hidden by default. When a menu item is clicked, I plan to $broadcast an event containing the dataUrl/templateUrl to the directive/component, prompting it to make two ajax calls - one for retrieving the data and another for fetching the template. Once both requests are complete, the content will render and become visible on the page.

Any suggestions or guidance on accomplishing this would be really helpful.

Just a heads up, I'm working with Angular 1.5.7

Answer №1

To achieve this, it is recommended to utilize routing, for example with the ui-router. The ui-router includes a resolve property that allows you to resolve controller dependencies and then inject them into your controller for use.

Here is an example I created (apologies for the simplistic UI):

HTML:

<div ng-app="app">
  <div ng-controller="homeCtrl as vm">
    <menu items="vm.items"></menu>
  </div>
  <div>
    <ui-view></ui-view>
  </div>
</div>

JS:

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

app.controller('gamesCtrl', function(data) {
  this.title = data.title;
}).
controller('reportsCtrl', function(data) {
  this.title = data.title;
}).
controller('usersCtrl', function(data, adminData) {
  this.title = data.title;
  this.removedUsers = adminData.removedUsers;
}).
controller('homeCtrl', function() {
  this.items = [{
    name: 'Manage games',
    state: 'games'
  }, {
    name: 'Weekly Reports',
    state: 'reports'
  }, {
    name: 'Manage Users',
    state: 'users',
    adminRequired: true
  }];
});

app.component('menu', {
  bindings: {
    items: "="
  },
  template: '<div ng-repeat="item in  $ctrl.items"><span ng-click="$ctrl.goToState(item)">{{item.name}}</span></div>',
  controller: function($state) {
    this.goToState = function(item) {
      console.log('redirecting to state:' + item.state);
      $state.go(item.state);
    }
  }
});

app.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider.
  state('games', {
    url: '/games',
    template: '<div><h1>{{vm.title}}</h1></div>', // use templateUrl..
    resolve: {
      data: function($q) {
        return $q.when({
          title: 'games'
        })
      }
    }, // return injectables who return promises and inject them into your ctrl
    controller: 'gamesCtrl as vm'
  }).
  state('reports', {
    url: '/reports',
    template: '<div><h1>{{vm.title}}</h1></div>', // use templateUrl..
    resolve: {
      data: function($q) {
        return $q.when({
          title: 'reports'
        })
      }
    }, // return injectables who return promises and inject them into your ctrl
    controller: 'reportsCtrl as vm'
  }).
  state('users', {
    url: '/users',
    template: '<div><h1>{{vm.title}}</h1><div>Removed Users:</div><div ng-repeat="user in vm.removedUsers">{{user}}</div></div>', // use templateUrl..
    // return injectables who return promises and inject them into your ctrl
    resolve: {
      data: function($q) {
        return $q.when({
          title: 'users'
        })
      },
      adminData: function($q) {
        return $q.when({
          removedUsers: ['user1', 'user2', 'user3']
        })
      }
    },
    controller: 'usersCtrl as vm'
  }).
  state('default', {
    url: '/default',
    template: '<h1>This is the default state</h1>'
  });

  $urlRouterProvider.otherwise('/default');
});

JSFIDDLE.

Pointers:

  • Consider using templateUrl instead of template when setting up states.
  • In the example, $q.when was used to illustrate returning a promise. Typically, $http.get\post would be utilized instead.

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

Replacing strings using Regex capture groups in JavaScript

Within my NodeJS application, there is a phone number field containing multiple phone numbers stored in one string. For example: \n\n \n (555) 555-5555 (Main)\n\n, \n\n \n (777) 777-777 (Domestic Fax)\n&bso ...

I need help with creating an AJAX JSON call using Angular. Let me share the JavaScript function that I currently have

When a button is clicked, the function below is called. It retrieves data from a JSON file and stores it if a success message is received. Here is a screenshot of the returned data. My JavaScript function is working correctly, but I am new to Angular and l ...

I am unable to retrieve images using the querySelector method

Trying to target all images using JavaScript, here is the code: HTML : <div class="container"> <img src="Coca.jpg" class="imgg"> <img src="Water.jpg" class="imgg"> <img src="Tree.jpg" class="imgg"> <img src="Alien.jpg" class=" ...

Show the correct URL address in the browser's address bar

My website utilizes Jquery/Ajax to dynamically load html pages into a specific div. By clicking on links with a certain class, the content opens up in this designated div, while the URL displayed in the address bar remains www.example.com. This setup allow ...

Include features once JSON has been loaded

Received this JSON data: { "info": [ { "id": 999, "products": [ { "id": 1, }, { "id": 2, } ] } ] } Info -- products -----id Here is the factory code snippet: AppAngular.factory('model', ['$http', f ...

Creating a static webpage hosted in an S3 bucket and implementing an AJAX request within the page to invoke a Lambda function

I recently uploaded an HTML page to an S3 bucket that includes an AJAX post request to the API Gateway URL in order to send an email. The issue arises when I try to use the same API Gateway URL with Postman to make a post request for sending emails, it wo ...

How to troubleshoot passing json data from a controller to an AngularJS directive

I recently started learning AngularJS and I'm facing an issue with passing JSON data from the controller to a directive. When I try to display the data, nothing shows up and I encounter the following errors: 1. Uncaught SyntaxError: Unexpected token ...

The search functionality is malfunctioning within the JavaScript table

I am working with a table that I want to filter based on input values. However, the current filtering function is not working as expected. I have utilized an onkeyup function for the filtering process. For more details and a live example, check out the jsf ...

Step-by-step guide for setting up CodeMirror

I'm feeling a bit lost with what to do next: <link rel="stylesheet" href="lib/codemirror.css"> <script src="lib/codemirror.js"></script> <script> var editor = CodeMirror.fromTextArea(myTextarea, { mode: "text/html" }); ...

Adding new pages in express.js without increasing the complexity of the routes

I am currently developing a project using Express.js and have been enjoying the experience. While the site is running smoothly, I am now looking for a way to allow users to contribute by adding pages to the site through either a form with set fields or by ...

Using multiple servers with Socket.io and Node.Js

Although I am new to the world of Web Sockets, I have a good grasp on the main concept. I am currently working on developing a straightforward multiplayer game and I thought it would be neat to implement server selection. My idea is to have sockets runnin ...

Is it possible for Angular models to have relationships with one another? Can one model make references to

I have a complex navigation structure set up like this to create the top nav: [ {id: 1, label: 'Home', icon: 'fa-home', subitems: []}, {id: 2, label: 'Sitemap', icon: 'fa-sitemap', subitems: []}, ...

Refresh shopping cart information using AJAX in WooCommerce

Attempting to implement an AJAX update for the shipping details in my checkout cart... I have set up the necessary function in functions.php function custom_update_shipping() { WC()->cart->calculate_shipping(); echo "hello"; die(); } a ...

Navigating an indefinite amount of state variables in React.js: A comprehensive guide

Receiving data from the server with an unknown number of items in the API leads me to utilize the map method in HTML for rendering. Below is the return section: if (loading) { return ( <div> <div> <Header /> ...

Encountered an issue during the Jest test where the error message states 'Cannot call Class constructor Stack without using the keyword 'new''

I have encountered an issue with my Jest test for an AWS CDK configuration import { expect as expectCDK, matchTemplate, MatchStyle } from '@aws-cdk/assert'; import * as cdk from '@aws-cdk/core'; import { KmsMultiregionPrincipalKey } fro ...

Wait for a reply from one GET request before initiating the next one in node

When working with node, I am making two consecutive calls to an API. My goal is to ensure that the first GET request has completed before triggering the second one, using data from the response of the first call. To achieve this, I have experimented with ...

The hyperlink appears to be malfunctioning with an additional border surrounding it within a pop-up window

I am facing an issue with a link <a> not functioning properly with a popup dialog on . Additionally, there seems to be a border that appears around the <a> when the popup initially displays. If you click on "Leer más" for any product, you can ...

When THREE.js repeatedly loads and plays the same animated GLB file in a loop, only the final model that is loaded will

I'm attempting to create a loop of animated butterflies, but I'm encountering an issue where only the first or last butterfly actually animates. I suspect this is due to the need to clone the gltf.scene, but there's a known bug with cloning ...

Converting data into a multidimensional array in AngularJS: A comprehensive guide

Struggling to convert a JSON array into a multidimensional array, looking for some guidance. I attempted using _.groupBy in underscore.js, but it's not proving successful with the nested array. If there is any way to convert from the given data [{ ...

Utilizing Docker to Deploy Nginx with Angular JS for Serving Static CSS, Images, and JS Files with Dynamic URL Paths

Our transition to Docker Containers is in progress for our legacy deployment. Each service will now run in separate containers, including Postgres, Redis, JobProcessor, LogProcessor, Nginx with Consul template, Consul, Registrator, Rabbitmq, and the Platfo ...