How to properly execute a function inside ng-repeat

How to properly execute a function inside ng-repeat

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

How to Properly Execute a Function Inside ng-repeat

Handling asynchronous operations within nested loops in AngularJS requires a specific pattern to avoid scope pollution and performance degradation. The scenario involves fetching sub-categories for every category inside a doubly nested ng-repeat, where each request must be independent of the others.

Attempting to execute an HTTP call directly on initialization or via a global function assignment often leads to two distinct failure modes: excessive re-execution due to dirty checking, or data contamination where one scope overwrites another.

The Trap of Global Scope Variables

The most common mistake is assigning the result of an asynchronous function directly to a variable in the controller, such as var temp_result. When you do this inside a loop, you are essentially sharing that single variable across every iteration of the outer loops.

In the second attempt described in the source material, the developer assigns the returned data to $scope.list_sub_categories. Because this is a global property accessible by all scopes created during the digest cycle, the last item processed overwrites the data for previous items. When the DOM updates, it reads this single shared value instead of maintaining separate lists for each category. This explains why clicking the debug button displays results for all categories simultaneously rather than just the one that triggered the event.

To fix this, you must isolate the result for every specific iteration. The standard pattern is to define a variable with a unique key based on the current item in the loop. For example:

$scope.get_Sub_Categories = function(category, callback) {
    $http({
        url: base_url + 'main/json_get_list_sub_categories',
        data: { category_id: category.category_id },
        method: "POST"
    }).success(function(data) {
        // Store the result in a property specific to this category
        category.subCategories = data;
        
        // If you need to render immediately, notify AngularJS of the change
        $scope.$apply(); 
    });
}

In the HTML template, you then bind directly to that scoped property:

<li ng-repeat="category in list_categories">
    <span>{{ category.name }}</span>
    <div class="checkbox">
        <label>
            <div ng-if="category.subCategories" 
                 ng-repeat="sub_category in category.subCategories">
                {{ sub_category.name }}
            </div>
        </label>
    </div>
</li>

By attaching the data to category.subCategories, you ensure that each category object holds its own array. Even if the controller runs concurrently, the data remains isolated within its parent object.

Avoiding Dirty Checking and Repeated Requests

The first attempt failed because of how AngularJS handles digest cycles. When using ng-init inside an ng-repeat, the scope is re-evaluated repeatedly as changes occur elsewhere in the application (such as input fields or other directives). This triggers the $http call multiple times, leading to the observed behavior of the page being "loaded 682 times."

To prevent this, you should separate the data fetching logic from the view initialization. Do not place HTTP calls directly inside ng-init. Instead, defer execution until the necessary data is loaded into the scope. You can achieve this by using a custom directive or a service that initializes the request only once when the parent scope's data is ready.

Alternatively, leverage the $async filter (available in Angular 1.5+) or simply ensure your controller initializes the list with empty arrays and populates them after the API returns data. This prevents the view from trying to render sub-categories before they exist, and it stops the framework from re-running the initialization logic on every digest cycle.

Managing Concurrency with Promises

If you need to fetch data for hundreds of categories simultaneously, creating 682 parallel HTTP requests can overwhelm your browser's network stack and cause timeouts. In such cases, consider batching requests or using a service like $q.all() to manage the promises collectively. However, if the list is large but sequential dependency exists (e.g., you only show sub-categories when a parent is selected), lazy loading is often superior to eager loading.

In this specific case, since the goal is to display all content immediately upon page load, ensuring each category has its own isolated property and deferring the request until after the view renders are the critical steps. By binding to category.subCategories rather than a global variable, you guarantee that the DOM reflects the correct data for each specific row without interference from sibling elements.

Our network