Triggering an event upon completion of ng-repeat's execution

I am facing a challenge in updating the style of a specific element after ng-repeat has finished changing the DOM. The directive I have implemented for triggering ng-repeat works perfectly fine when adding items to the model, but it does not get called when removing an object from the list.

To demonstrate this issue, I have created a function that randomly adds and removes data from the list. You will notice that the removal operation does not trigger the ng-repeat directive call. Is there any way to address this problem?

var module = angular.module('testApp', [])
.directive('onFinishRender', function ($timeout) {
return {
    restrict: 'A',
    link: function (scope, element, attr) {
        if (scope.$last === true) {
            scope.$evalAsync(attr.onFinishRender);
        }
    }
}
});

Fiddle Link

Answer №1

If you want to achieve this functionality:

<div ng-repeat="item in items" on-finish-render="runTest()"
    ng-init="initialize($last, item)">{{item}}</div>
$scope.initialize = function(isLast, element){
    if(isLast)
        console.log(element)
}

ng-init is a directive that triggers when the element is initialized.
$last is a boolean flag set to true if the current element is the last one in an ng-repeat loop.

Check out the updated Fiddle here

Answer №2

Is there a better alternative to using $watch in this situation?

$scope.$watch('ta', function (newVal, oldValue) {
    if(oldValue.length > 0)
    {
        var i = 0; // perform an action
    }
}, true);

This approach allows for more control over when items are added or removed from the array.

Check out this example on JSFiddle

Answer №3

When you add a new item to the list, it automatically triggers its own update() function upon rendering. Remember, each item in the array has its individual onUpdateRender directive with unique properties.

If you need to perform specific actions after changing the length of the list, consider alternatives to using a directive.

Answer №4

An easy and efficient method

<li ng-repeat="data in dataList" ng-init="$last && $parent.myOnFinishHandler();" ></li>

$parent refers to the scope where the datalist is located

angular.module("xyz", []).controller('mc', function($scope) {
  $scope.dataList = ["abc", "123", "xyz", "orange", "apple"];
  $scope.myHandler = function() {
    console.log("render finish ");
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="xyz">
  <ul ng-controller="mc">
    <li ng-repeat="data in dataList" ng-init="$last && $parent.myHandler();"> {{data}} </li>
  </ul>
</div>

Answer №5

I stumbled upon the answer while browsing through another solution.

It turns out there isn't a straightforward way to achieve this functionality. I ended up creating a filter that essentially does what I need it to do. Here's the basic idea:

app.filter('ngRepeatFinish', function($timeout){
    return function(data, scope){
        //var scope = this;
        var flagProperty = '__finishedRendering__';
        if(!data[flagProperty]){
            Object.defineProperty(
                data, 
                flagProperty, 
                {enumerable:false, configurable:true, writable: false, value:{}});
            $timeout(function(){
                    delete data[flagProperty];                        
                    scope.$emit('ngRepeatFinished');
                },0,false);                
        }
        return data;
    };
})

This filter broadcasts for every element created, allowing me to run my watch function based on the listening event in the controller.

$scope.$on('ngRepeatFinished', function() {
    //Perform some magic here
})

In order to use this directive, I have to pass the scope from the HTML by adding "this" before ngRepeatFinish.

<div ng-repeat="item in (items | ngRepeatFinish:this)"></div>

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

Combining Angular, WebAPI, and CORS for seamless integration

Running a web application in angular requires calling a separate ASP.NET Web API on different ports, with the web server on port 44302 and the web API on port 44307. CORS settings have been configured on the web API server to allow cross-origin requests: ...

Retrieve the total count of tables within a specific div element

If I have an unspecified amount of tables within a div, how can I determine the total number of tables using either plain JavaScript or jQuery? ...

Implementing efficient loading and dynamic updates in web applications with Angular.js and php through

Currently, I am working on a project that requires lazy loading of images. However, a new requirement has come up which involves a server batch process pulling images from a database at regular intervals. These images must then be appended to the photos ...

Utilizing JSONLOADER in Three.js allows for efficient loading and

Currently, I am using JSONloader in three.js to load models and it works perfectly. However, I am struggling to find detailed steps or documentation on how to preload textures (which are images) in order to create an interactive feature where I can switc ...

How to change the background color of a slider using jQuery

As a newcomer to web programming, I am currently working on incorporating a slider into my website using jQuery. My goal is to change the background color of the slider to red when the value is less than 5 and green when it exceeds 5. Can this be achieved ...

Error: Unable to access property 'nTr' as it is not defined

When I invoke the fnSelect function, an error occurs in Chrome: Uncaught TypeError: Cannot read property 'nTr' of undefined This is the code snippet causing the issue: $('#ToolTables_table_id_0, #ToolTables_table_id_1').mousedown(fun ...

Javascript is handling the JSON Request flawlessly, however, when using Nodejs, an error is encountered with a status

I'm trying to fetch a simple JSON File in NodeJS. Using Javascript and jQuery, it functions perfectly: $(document).ready(function() { $.getJSON('https://www.younow.com/php/api/broadcast/info/curId=0/user=Peter', function(json) { if ...

What is the purpose of passing data into the 'success' function of an AJAX request?

Recently, I embarked on a journey to learn jQuery and AJAX, but I found myself tangled in confusion when it came to AJAX requests. To gain practice, I decided to create a simple TodoApp using Node, jQuery, and Bootstrap. While I managed to grasp GET and P ...

Switch out single quotation marks and double quotation marks

I have a variable stored in my MySQL database that needs to be able to handle both simple and double quotes. For instance: $variable = "I'm feeling great" or $variable = I'm feeling great or $variable = "I am feeling great" In my database, the ...

Search for Div IDs while filtering as you type

Is there a search jQuery plugin that enables real-time filtering based on Div ID as you type in the search box? It would be great if the filter instantly refreshes. ...

The numerical value fluctuates upon utilizing JSON.parse( )

I am currently utilizing Node/Express to send API requests to the unofficial Vine API. The data returned by the GET https://api.vineapp.com/users/search/ route undergoes changes during parsing. This is my code snippet: request({ url: 'https://api.v ...

how to show an error in a modal window when encountering an error

Using Blazor and Blazorstrap, typically when the server disconnects, an "Error" message is displayed. However, with the BsModal from Blazorstrap, it appears in the background layer, making it unresponsive. How can this be fixed? Is it possible to close the ...

Utilizing Jquery to pass two classes along

I am looking for assistance on how to pass multiple classes within if-else statements and jQuery. My goal is to have both divs and divs2 change when the next button is clicked. Can someone please provide guidance on achieving this? --code not mine-- ...

Currently, only the initial button is functional. I am uncertain if it is due to a script issue or if there is a rule that I inadvertently

As a beginner, I am eager to grasp the fundamentals and rules of Javascript. My goal is to create a basic example that involves a box with three buttons. However, I have encountered an issue where only one button seems to be functional despite having dis ...

Maintain the aspect ratio of an image when placing it in a square container

Looking for a way to create a CSS grid with non-square random sized images? I need help filling all the space inside a fixed size div. Any suggestions? Check out my example: (blue represents the fixed size div and red shows the image inside it) ...

What are some tips for incorporating vue.js into a basic web application?

I've been trying to incorporate vue.js into my web application, but for some reason, it's not loading and the HTML is not firing in the browser. Please take a look at the code snippet below: <!DOCTYPE html> <html> < ...

Develop an array using a variable's value in JavaScript

I need assistance with creating an array of variable length based on a dynamic value ranging from 1 to 15. The goal is to populate the array differently depending on the specific value of the variable. For instance, if the variable's value is 1, I wo ...

Turn only one bracket on the accordion

When clicking on a specific header, I want only one chevron to rotate instead of all the chevrons rotating. I am currently unsure how to specify which chevron should rotate individually. My project is in ASP.NET MVC 5 and I am using razor view to loop th ...

What is the best way to ensure TypeScript recognizes a variable as a specific type throughout the code?

Due to compatibility issues with Internet Explorer, I find myself needing to create a custom Error that must be validated using the constructor. customError instanceof CustomError; // false customError.constructor === CustomError; // true But how can I m ...

Learn how to incorporate a click event with the <nuxt-img> component in Vue

I am encountering an issue in my vue-app where I need to make a <nuxt-img /> clickable. I attempted to achieve this by using the following code: <nuxt-img :src="image.src" @click="isClickable ? doSomeStuff : null" /> Howeve ...