Signs that indicate Angular has completed deferring

I'm having trouble grasping Angular's deferring and promises. I want to hide a "loading" message once all promises have been completed. Here's an example of my code:

$scope.buildTeam = function () {
    $scope.Message = "loading...";

    var deferred = $q.defer();
    var promiseList = [];

    c = $scope.teamModels[0];

    for (index = 0; index < c.quantity; ++index) {
            var assignment = new teamAssignment(c.assignmentTypeId, $scope.parentAssignment.AssignmentId, c.description);
            promiseList.push(departmentService.addAssignment(assignment).then(function (result) {

                //added lead/captain. Now insert visually on page
                insertToScope($scope, result);

            }));
        }

    } 

    $q.all(promiseList).then(function () {
        deferred.resolve();
        $scope.Message = "Loaded.";
    });
}

The issue I'm facing is that $scope.Message displays "Loaded" before the data is actually inserted onto the page in the case of a large data pull. Do I also need to defer insertToScope? The function InsertToscope simply reads:

function insertToScope($scope, a) {
   //get root scope
   var rs = angular.element("#ngRootContainer").scope();
   rs.parentAssig.push(a);
}

And the department service looks like this:

departmentModule.factory('departmentService', function ($http, $q) {
return {
    addAssignment: function(assignment){
        var deferred = $q.defer();
        $http.post('/Department/addAssignmentReturnAssignmentRow', assignment).success(deferred.resolve).error(deferred.reject);
        return deferred.promise;
    }
});

So my question remains, what steps do I need to take to call a function only after all the promises are complete? Thanks in advance for your assistance.

Answer №1

$q.all is the solution to your problem. If your code is not functioning as expected, there are two possible reasons:

  • You may be passing a promiseList that does not include all the promises you intend to wait for. Take some time to debug your code and ensure that all promises are being passed in correctly. Confirm that it is an array being passed as the first parameter.
  • The promises you are passing in may be resolving earlier than anticipated. To check this, log 'A' in insertToScope and 'B' in the then block of your $q.all. You should expect to see
A
...
A
B

in the console.

For guidance on using $q.all(), refer to this simple plunkr example: http://plnkr.co/edit/9QH9Y0w7DG0WCouMuX82?p=preview

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

Displaying HTML with AngularJS dynamic data-binding

Here is a sample view: <div ng-show=""> <div style='background-color: #13a4d6; border-color: #0F82A8'> {{headerdescription}} <div style='float: right'>{{price}} $</div> </div> <div style=&apos ...

Recursion functions seem to be not providing a return value

I wrote a recursive function that needs to return an object from an array of objects. Each object in the array includes a reference to a neighboring object, as shown below: { id: 5, neighbors: { north: 1, east: 6, south: 9, west: 4 ...

Step-by-step guide for serving static JavaScript files using NextJS

I am currently exploring the process of hosting static js and css files using NextJS. My journey began with creating a react app through create-react-app, where I developed an App component before executing the npm run build command. This resulted in the ...

Use JavaScript to load and set a background image for a div

When it comes to loading different images onto an "img" tag by printing their URLs using JavaScript and then letting CSS manipulate the content in the tag, I have a code snippet that does just that. $(window).load(function() { var randomImages = [&apo ...

Implementing $http in AngularJS

I am encountering the following issue: angular.module('myApp').factory('dashboard', ['$http', function ($http) { return { name: function(str){ return str + ':' + 'works!'; ...

When using the npm command, errors may occur that are directly related to the lifecycle and initialization

Currently, I am delving into the world of OpenLayers and JavaScript. I came across a helpful tutorial that provides step-by-step guidance on creating a simple OpenLayers project using JavaScript. I followed the instructions diligently but encountered an er ...

Looking into the field of a document that is referenced

Within the database, there are two collections: 'actors' and 'movies' Here is an example of one actor: { _id: ObjectId("54f38bd9b814dca762778032"), name: { first: 'Jason', last: 'Statham' } } And her ...

Using React.js to create a modal that includes ExpansionPanelDetails with a Checkbox feature

I am trying to achieve a specific visual effect with my code. Here is an example of the effect I want: https://i.stack.imgur.com/cJIxS.png However, the result I currently get looks like this: https://i.stack.imgur.com/547ND.png In the image provided, y ...

Conceal the button once the page has been converted to an HTML format

Located at the bottom of the HTML page is a button that triggers an onClick function. Since the page only contains internal CSS, when users save the page (by right-clicking and selecting Save As) as an HTML file, it is saved without any additional folders ...

Organize information before making a choice in the dropdown menu

Currently, I have a dropdown menu in HTML that allows you to order the data by different options: <select ng-model="sortOrder" ng-options="option.value as option.name for item in options"></select> In addition, I have implemented code using n ...

Is there a way to retrieve text from within a div using code behind in asp.net with c#?

I am currently developing a SQL QUERY editor where users can enter queries. The entered text is then passed to a SQL COMMAND for execution, and the results are displayed to the user in a GRIDVIEW. However, I am facing an issue in retrieving the text entere ...

Utilizing Binding Time in Angular for Enhanced Views

I am completely new to Angular JS. I have a simple question that I have been searching for answers on SO. My goal is to display the current time in real-time (refreshing every second as the clock ticks) on my view. Here's what I have tried so far: H ...

Update an item's precise orientation in relation to the global axis

Update: Included a jsfiddle for clarification: JSFiddle I am working with an object (a cube) in a scene and my objective is to provide it with 3 angles that represent its orientation in the real world. These angles are measured against the X, Y, and Z ax ...

Distinguishing between native and custom error objects: a comprehensive guide

When working with errors in my node app, I find it challenging to handle both custom and native errors seamlessly. Errors are not just ordinary JavaScript objects, which adds complexity to error handling. To manage custom errors, I am experimenting with t ...

Determine the total quantity of colored cells within a row of an HTML table and display the count in its own

I need assistance with a table that has 32 columns. From columns 1 to 31, I am able to fill in colors by clicking on the cells. However, I now want to calculate and display the number of cells that are not colored in the last column. This task must be co ...

Choose a specific option from an AngularJS dropdown menu

I am incorporating AngularJs with ASP.NET MVC4. Initially, I am creating a dropdown using razor syntax. @Html.DropDownList("packageName", (IEnumerable<SelectListItem>)ViewBag.packageName, "No Data Available", new { ng_model = "subForm.packageNam ...

Implementing Knockout.js with JqueryUI Autocomplete: Access the complete object instead of just the value

I have implemented a custom binding for a JQueryUI auto complete feature that works well. However, I am looking to modify it so that it returns the Item object, which can then be pushed to another array. Can someone provide guidance on how to achieve this ...

Experiencing difficulties with incorporating ng-view into a one-page AngularJs application

I'm completely new to AngularJs and decided to try implementing a one-page app into one of my projects after following some tutorials. I have it up and running, but I have a question about the code. Is there a way to change what is displayed on the in ...

When trying to show a Vue view, there was an issue with reading properties of null, specifically the 'style' property

I am experiencing an issue with a header that has an @click event in the body. Instead of displaying a Vue view upon clicking, I am encountering the following error: Cannot read properties of null (reading 'style') Upon researching on Stack Ove ...

Looking to trigger a PHP page by clicking on a div?

Is there a way to trigger a PHP page call when a user clicks on a <DIV> with AJAX? Additionally, can the text of the DIV be changed to display "LOADING....." simultaneously? I lack knowledge about AJAX. Could you please provide me with more details ...