angularjs invoking a function within a nested ng-repeat once it's completed

My issue involves 2 nested ng-repeat loops and a boolean variable. The goal is to hide the loading div once all content is rendered, but currently the loading div disappears before that happens. The boolean variable is dependent on a callback function that fetches all the necessary data.

<tr ng-repeat="package in packages track by $index">
   <td> {{ pack.Name }}</td>
   <td>
      <select ng-hide="package.spinStart" class="form-control" ng-model="package.selectedVersion">
            <option ng-repeat="pack in package.allPackageVersions track by $index"
                    value="{{pack.Version}}"
                    ng-hide="pack.shouldHide"
                    ng-disabled="!expertModeOn && pack.shouldDissable"
                    ng-style="!expertModeOn && pack.shouldDissable && {'color':'#ddd'}">

                    {{pack.NuGetPackageId}} | {{pack.Version}} | {{pack.Published}}
            </option>
      </select>

I am looking for a way to call the function only after both nested loops have finished executing. I have experimented with using $watch statements and directives without success. Any suggestions are appreciated!

Answer №1

Is it possible to utilize $last in this scenario?

<!DOCTYPE html>
<html data-ng-app="myApp">

<head>
  <link rel="stylesheet" href="style.css">
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
  <script src="script.js"></script>
</head>

<body data-ng-controller="testController">


  <div ng-repeat="package in packages">
    {{package.name}}
    <div ng-repeat=" pkg in package.selectedVersion" ng-init="$last && call()">
      {{pkg.name}}
    </div>
  </div>

  <script>
    angular
      .module('myApp', [])
      .run(function($rootScope) {
        $rootScope.title = 'myTest Page';
      })
      .controller('testController', ['$scope',
        function($scope) {
          $scope.packages = [{
            name: 'test1',
            selectedVersion: [{
              name: 'test_ver1'
            }, {
              name: 'test_ver2'
            }, {
              name: 'test_ver3'
            }]
          }, {
            name: 'test2',
            selectedVersion: [{
              name: 'test_ver1'
            }, {
              name: 'test_ver2'
            }, {
              name: 'test_ver3'
            }]
          }];

          var counter = 0
          $scope.call = function() {
            counter++
            if (counter == $scope.packages.length) {
              alert("All loops finished");
            }
          }
        }
      ])
  </script>
</body>

</html>

Answer №2

If you want to signal the completion of an outer loop, consider using a custom directive that triggers an event.
This directive can be easily reused in various loops by simply subscribing to the event.

app.directive('onLoopFinish', function($timeout) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            // $last is a boolean set by angular inside ng-repeats
            if (scope.$last) {
                // Wait for view to fully render
                $timeout(function() {
                    // Emit event upwards through the scope tree
                    scope.$emit('loopFinished');
                });
            }
        }
    };
});

In your controller, listen for the event:

$scope.$on('loopFinished', function() {
    $scope.hideLoader = true;
});

Usage in template:

<div ng-repeat="item in items" on-loop-finish>

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

The error message "Uncaught TypeError: Unable to access property 'url' of an undefined object - Google Image API" appeared

I am facing an issue with generating 5 random images. The first row, from flicker, is working fine. However, the second row from Google is only returning 4 images and showing an error in the console: Uncaught TypeError: Cannot read property 'url&apos ...

using configureStore instead of createStore

After updating my packages, I received a notification from VScode indicating that the createStore function was deprecated. This prompted me to go ahead and replace it with the recommended alternative. In my store file, I left the original line as a commen ...

When the HTML content matches a specific value, initiate a click event to trigger

Can anyone help me troubleshoot? I've tried multiple methods but can't seem to get it right. Here's a breakdown of what I'm attempting to accomplish: #info-NUMBER-btn shows Click to display more information. #info-NUMBER CSS is set t ...

Introduce an additional parameter to the Prestashop Cart entity

After setting up a radiobox "stock_action" in the Cart, I need to send its value to the Cart object for additional order costs. In the Cart Override, the $stock_action variable has been added: public $stock_action; /** * @see ObjectModel::$defi ...

Alternatives to AMP in AngularJS

My current project is based on Angular 1.x and I recently received advice from an SEO specialist to enhance the initial mobile load speed of my website. One suggestion was to implement AMP, but after some research, it appears that integrating AMP with Angu ...

Dynamically defined type literals in Typescript

Recently, I came across an intriguing problem. I am attempting to develop a Vue.js wizard component that takes in configuration objects. The type of demo I have looks like this: type WizardConfiguration = { steps: Array<{ name: string, fie ...

Combining Entities Using Immutable JavaScript

Currently utilizing React, Redux, and Immutable. I have a question about merging a plain JavaScript object into an Immutable Map object. Importing Immutable.js: import { List as iList, Map as iMap } from "immutable"; The content of action.paylo ...

How about a unique scrolling experience?

Currently, I am attempting to prevent the scroll position from being locked after a single scroll for one second while scrolling down one section at a time. However, I am encountering unexpected behavior. const [nextSection, setNextSection] = useState(&ap ...

Rotating images on a canvas

We're currently implementing Ionic and Angular in our project. One issue we are facing is regarding image rotation on canvas. When we click on an image, the rotation works perfectly if it's a jpg file. However, when we pass a base64 image, the r ...

JavaScript is limited to functioning within the content area of WordPress websites

Currently, I am using WordPress and I am looking to have my share links follow the post as a user scrolls down. The issue I'm facing is that the JavaScript code is directly attached to content.php, causing it to load multiple times on pages with multi ...

The HTTP GET request is failing to trigger

I'm currently working on building a basic messageboard using MongoDB, Angular, NODE.js and Express. Oddly enough, everything works fine the first time I call getMessages(). But when I try to call getMessages() after posting a message with postMessage ...

Preventing Servlet Redirection in HTML: A Step-by-Step Guide

Is there a way to send data from an HTML web page to a server using a servlet without redirecting? <form method="post" name="customerForum" action="addCustomer"> <button class="btn btn-success" id="ad ...

Deciphering unidentified Json data

Having some trouble with an error in my note taker app built using expressjs. Everything was working fine until I tried to save a new note and it's throwing this error: SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse () Here&apos ...

What is the specific event in Angular used to bind the chosen date from a Calendar component?

I'm currently working on an Ionic 4 app using Angular. In the code snippet below, I am trying to figure out how to bind a date after selecting it from the Calendar. Can anyone tell me what event I should use to achieve this? <ion-item> < ...

How to transfer the application version from package.json to a different non-JSON file in Angular and node.js

While developing my Angular application, I encountered a task where I needed to extract the version number from the package.json file and transfer it to a non-json file. The content of my package.json file is as follows: { "name": "my app ...

Exploring the world of jQuery and Ajax to retrieve a full HTML framework

I'm a beginner in jQuery and JavaScript programming. While I've managed to use jQuery for my Ajax calls, I'm facing an issue that has me stumped. When making an Ajax call, I'm trying to return a complete HTML structure, specifically a ...

What is the most effective method for testing event emitters?

Imagine I have a basic component structured like this: @Component({ selector: 'my-test', template: '<div></div>' }) export class test { @Output selected: EventEmitter<string> = new EventEmitter<string>() ...

Design a hover zone that allows for interaction without disrupting click events

I am looking to create a tooltip box that appears when hovering over an element, and I want the tooltip to only disappear when the user's mouse exits a specific custom hover area outlined by a vector graphic. My current implementation is working, but ...

What is the most effective method for displaying error messages in Extjs?

I am currently using the store.synch() method to post data, with validation being done on the server side. I am currently displaying error messages in a message box, but I want to explore alternative ways to show errors without having to use markInvalid( ...

Utilize URL parameters in Node.js and Express for effective communication

I have an endpoint ..com When I perform a curl call, the endpoint looks like this: ..com?param1=true Now, I am attempting to make a similar call from Node.js. However, I'm uncertain about whether param1 should be included in the headers, concatenate ...