Ways to ensure that ng-view stays idle until an XHR response is received

Is there a way to make the ng-view wait for an xhr request? I have two controllers set up for a routed ng-view - the first one loads perfectly, but the second one doesn't render properly because the xhr response is happening after partial.html has been downloaded. How can I prevent the partial.html request until the client receives the xhr response?

Take a look at the code snippet below for the route configuration:

var configuration = [
  '$routeProvider',
  '$locationProvider',
  function(routeProvider, locationProvider) {
    routeProvider.when('/', {
      templateUrl: '/partials/hotelinfo.html',
      controller: 'HotelInfo'
    }).when('/service/dept/:id', {
      templateUrl: '/partials/department.html',
      controller: 'Department'
    }).otherwise({
      redirectTo: '/'
    });

    locationProvider.html5Mode(true);
  }
];

Here's the controller configuration that handles the xhr response:

<!-- language: lang-js -->

var Department = [
  '$scope',
  '$routeParams',
  function (scope, routeParams) {
    http.get('/service/dept/' + routParams.id).success(function (data) {
      scope.data = data;
    });
  }
];

Answer №1

Opt for utilizing a resolve function in $routeProvider to handle the $http.get method instead of directly calling it from your controller. This approach ensures Angular delays loading your view until the promise returned by $http is fulfilled.

Answer №2

To achieve this, you can utilize the resolve function in routeProvider, which returns a promise. The view will only load once that promise is resolved, and you have the option to resolve it in your controller.

For more information, refer to http://docs.angularjs.org/api/ngRoute/provider/$routeProvider.

var config = [
  '$routeProvider',
  '$locationProvider',
  function(routeProvider, locationProvider) {
    routeProvider.when('/', {
      templateUrl: '/partials/hotelinfo.html',
      controller: 'HotelInfo'
    }).when('/service/dept/:id', {
      template: '/partials/department.html',
      controller: 'Department',
      resolve: {
            deferred: function($q) {
                return $q.defer();
            }
        }
    }).otherwise({
      redirectTo: '/'
    });

    locationProvider.html5Mode(true);
  }
];


var DepartmentController = [
  '$scope',
  '$routeParams',
  'deferred',
  function (scope, routeParams, deferred) {
    http.get('/service/dept/' + routParams.id).success(function (data) {
      scope.data = data;
      deferred.resolve();
    });
  }
];

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

Choosing one item from an array to showcase in a view [Angular]

I've previously inquired about this issue without success. My current challenge involves a store app created with AngularJS. I am trying to implement a feature where clicking on an item will open it in a separate "item" view, displaying only the info ...

unable to gather information from suppliers

I'm currently building a login page with nextjs and spotify js, but I've run into the following error https://i.sstatic.net/cKiM8.png Here is the code snippet that is causing the issue: import React from 'react' import { getProviders ...

What is the best way to remove multiple rows from a table using Angular.js?

I'm attempting to tackle the task of deleting multiple rows from a table using checkboxes in Angular and PHP. Unfortunately, I've hit a roadblock and my understanding of Angular seems to have reached its limit! Let's take a look at my table ...

Retrieving a specific object from a subarray using MongoDB's ID

My MongoDB document includes the following: const Categories = [ { _id: 's654fs54s6d4f' title: 'category 1', SubCats: [ { _id: 'jhgfsf68746' name: 'subcat 1', i ...

Guide to incorporating onchange event in a React.js project

Just starting out with reactjs and looking to incorporate onchange into my application. Utilizing the map function for data manipulation. handleChange = (event, k, i) => { this.setState({ dList: update(this.state.dList[k][i], { [ev ...

Seeking guidance on recompiling a directive within Angular?

I have implemented a directive to display data in a tree-like structure. This directive allows for filtering of the data. However, when I clear the filter, the directive does not automatically update to reflect the changes in the data. It only updates when ...

Submitting a form using AJAX without specifying the form ID when there is a change

I have a unique setup on my page where a table is created with each cell acting as a form. The goal is for these forms to submit when the input value changes (onchange) without refreshing the entire page. An example scenario would be allowing users to ent ...

Error encountered while attempting to build Ionic 5 using the --prod flag: The property 'translate' does not exist on the specified type

I encountered an error while building my Ionic 5 project with the --prod flag. The error message I received is as follows: Error: src/app/pages/edit-profile/edit-profile.page.html(8,142): Property 'translate' does not exist on type 'EditProf ...

Firefox throwing an error with jQuery URL Get requests

Could someone help me understand why my JavaScript function is triggering the error function instead of the success function in Firefox on Ubuntu? $(document).ready(function() { console.log( "Begin" ); $.ajax({ type: "GET", dataType: "ht ...

Implementing external JavaScript files such as Bootstrap and jQuery into a ReactJS application

Just diving into ReactJs, I've got static files like bootstrap.min.js, jquery.min.js, and more in my assets folder. Trying to incorporate them into my ReactJs App but running into issues. Added the code below to my index.html file, however it's ...

Is it possible to inject $scope into a child model?

In the process of developing a fairly complex AngularJS application, I have realized that my primary controller model should be made up of multiple self-contained objects that will be utilized by other controllers. While this setup presents no major issues ...

Moving an array in AngularJS from one file to another

As someone new to AngularJS, I am facing an issue with integrating two separate files that contain modules. Each file works fine individually - allowing me to perform operations on arrays of names. However, when switching views, the arrays remain stored un ...

What could be causing the "Undefned Jquery-ajax" error to pop up

I am struggling with the following code. My goal is to populate values into a dropdown <select> box, but I keep receiving an error of undefined. I have tried switching between Object.keys and Object.values, however, I am still facing the same issue. ...

JavaScript Filtering JSON Data Based on Date Range

I am attempting to filter a basic JSON file based on a specified date range, with both a start date and an end date. Below is the function I have created for this task: var startDate = new Date("2013-3-25"); var endDate = new Date("2017-3-2 ...

Tips for reducing image file size using ImageMinimizerWebpackPlugin in Next.js (webpack 5)

When attempting to use this plugin for image compression, I am encountering an issue where the build process completes successfully, but the images remain uncompressed. As a beginner with webpack, I'm unsure of what might be causing this problem. Cou ...

Mastering the art of effectively capturing and incorporating error data

Is there a way to retain and add information to an Error object in typescript/javascript without losing the existing details? Currently, I handle it like this: try { // code that may throw an error } catch (e) { throw new Error(`Error while process ...

Accessing JSON data through crawling may trigger an "Invalid access" warning

Currently extracting data, I came across this base URL After inspecting chrome's developer tools - Network tab, I found the following URL: international?Adt=1&Chd=0&ECITY1=HKG&ECITY2=ICN&Fa…019.03.13.&TRIP=RT&W ...

transition effect of appearing and disappearing div

Having trouble creating a fade out followed by a fade in effect on a div element. The fade out happens too quickly and the fade in interrupts it abruptly. Here is the JavaScript code: $('#fillBg').stop(true,false).fadeTo(3000, 0); $("#fillBg"). ...

Difficulty loading partial view with Ajax in Asp.net MVC Core

After reading through this informative article, I am attempting to dynamically load a Partial View using Ajax. However, I am encountering an issue where the partial view is not being loaded as expected. Important Points to Note: I am utilizing VS2015 wi ...

How can you notice when a DOM element is deleted from the page?

I am in the process of creating a custom directive that will ensure only one element is active at a time. Directive: displayOneAtATime Description: This directive can be applied to a DOM node to guarantee that only one element with this directive can be v ...