What steps are involved in setting up a callback function for ng-repeat orderBy?

Seeking a solution to trigger a callback function after AngularJS's ng-repeat orderBy filter has finished rendering...

Code:

<div ng-controller="MyCtrl">
    <table>
        <thead>
            <tr>
                <th ng-click="sort('name')">Name:</th>
                <th ng-click="sort('age')">Age:</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="item in items | orderBy:sortColumn:reverseSort">
                <td>{{item.name}}</td>
                <td>{{item.age}}</td>
            </tr>
        </tbody>
    </table>
</div>

JavaScript:

var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
    $scope.items = [{
        "name": "John",
            "age": 25
    }, {
        "name": "Amy",
            "age": 75
    }, {
        "name": "Sarah",
            "age": 12
    }, {
        "name": "Matt",
            "age": 55
    }, {
        "name": "Xaviour",
            "age": 2
    }];

    $scope.sortColumn = 'name';
    $scope.reverseSort = false;

    $scope.sort = function (column) {
        $scope.sortColumn = column;
        $scope.reverseSort = !$scope.reverseSort;
    };

    $scope.sortRenderFinished = function(){
        console.log('Done Rendering!');
        //Custom action here
    };
}

JSFiddle Demo

If you have any insights on how to execute $scope.sortRenderFinished() once the orderBy filter has completed reordering the table rows, your assistance would be greatly appreciated! :-)

Answer №1

After some reflection, I realized that my approach was too complex...

I decided to implement a custom sorting function and manually handle the array instead of relying on the orderBy filter in the ng-repeat directive:

var myApp = angular.module('myApp', []);

function MyCtrl($scope, $filter) {
    $scope.items = [{
        "name": "John",
            "age": 25
    }, {
        "name": "Amy",
            "age": 75
    }, {
        "name": "Sarah",
            "age": 12,
    }, {
        "name": "Matt",
            "age": 55
    }, {
        "name": "Xaviour",
            "age": 2
    }];



    $scope.addChild = function () {
        var
        matt = $scope.items[findIndexByKeyValue($scope.items, 'name', 'Matt')],
            savannah = {
                "name": "Savannah",
                    "age": 2,
                    "parent": matt
            };

        console.log('matt');
        console.log(matt);

        $scope.items.splice($scope.items.indexOf(matt) + 1, 0, savannah);
        matt.child = savannah;
        $scope.matt = matt;
        $scope.savannah = savannah;
    };

    var findIndexByKeyValue = function (obj, key, value) {
        for (var i = 0; i < obj.length; i++) {
            if (obj[i][key] == value) {
                return i;
            }
        }
        return null;
    };


    $scope.sortColumnExp = '';

    $scope.sort = function (column) {
        $scope.sortColumnExp = ($scope.sortColumnExp.indexOf('-') == 0) ? column : '-' + column;
        console.log($scope.sortColumnExp);
        if ($scope.savannah) {
            $scope.items.splice($scope.items.indexOf($scope.savannah), 1);
        }
        $scope.items = $filter('orderBy')($scope.items, $scope.sortColumnExp);
        if ($scope.savannah) {
            $scope.items.splice($scope.items.indexOf($scope.savannah.parent) + 1, 0, $scope.savannah);
        }
    };

}

Check out this JSFiddle link for reference. Special thanks to @LcLk for the helpful guidance.

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

What is the best method for enabling HTML tags when using the TinyMCE paste plugin?

After spending countless hours searching for a solution, I am still puzzled by this problem. My ultimate goal is to have two modes in my powerful TinyMCE editor: Allowing the pasting of HTML or Word/OpenOffice text with all styles and formatting attribu ...

Double curly brace Angular expressions being repeatedly evaluated during mouse click events

Within our Angular application, the code structure is as follows: <div>{{ aGetProperty }}</div> <div>{{ aMethod() }}</div> Upon clicking anywhere on the page, these expressions are being evaluated repeatedly. For example, if there ...

Encountering an issue with the Laravel framework that lists available methods as: GET

I am encountering an issue while attempting to submit a form using ajax. The error message The POST method is not supported for this route. Supported methods: GET, HEAD. keeps appearing. Despite searching on platforms like Stackoverflow, no solution seems ...

Is it possible to retain the volume level setting?

Whenever I am playing music and adjust the volume to 20%, the settings reset to 100% when the bot leaves the voice channel. It's frustrating having to manually set it back to 20% each time. Is there a way for my bot to remember the volume setting? con ...

The AngularJS page comes to a halt whenever the view is switched

Encountering an issue with AngularJS where changing the view turns the page into a silhouette of gray or black, freezing or disabling the entire page. Nothing is clickable and manual refresh is required to return to normal functionality. Additionally, ther ...

Is it feasible to change the cursor to a custom one using either jQuery or basic JavaScript?

Can jQuery be used to change the cursor to a custom loading animation, like a 'spinner' gif, instead of just setting it to 'wait'? Thank you in advance. ...

Is it possible to use abbreviations instead of full names for object properties in a JSON string?

I'm looking for a way to efficiently convert large and repetitive javascript objects into JSON strings. With the abundance of repeating property names in these objects, I want to streamline the process by replacing those names with predefined abbrevia ...

Reorganize the data in a different manner (collections of items instead of individual items linked to groups)

Is there a way to create a function that converts data from `DevicesType` to `GroupsType` below? Instead of having a list of devices showing the groups they belong to, I need a list of groups with their respective devices. type DevicesType = { id: string ...

connecting a JavaScript object literal to a specific address within an HTML document

I'm encountering an issue with creating an object that contains properties such as {"name":"John Doe","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e08e818d85a0848f8d81889c8b848d8a">[email protected]</ ...

What steps can be taken to avoid the destruction of an object following its use of the .load() function in JavaScript (specifically in three.js)?

I'm facing an issue with preventing the destruction of my object after loading it. var loader = new THREE.ColladaLoader(); var rescue; loader.load( 'Improved_Person_Maker_better_quality.dae', function(collada) { scene.add(co ...

Utilizing PHP and AJAX to Extract Information from a MySQL Database

My goal is to fetch data from a MySQL database hosted on a webserver and display it in an HTML table. I've been following an example on W3Schools, but I'm facing issues retrieving the data successfully. Here is the source code: (HTML) <html& ...

What is the best way to replace a regular expression in JavaScript?

I've recently been exploring the functionalities of MathJax, a Javascript library that enables the use of LaTex and similar mathematical markup languages within HTML. However, when attempting to incorporate it into my Javascript code, I encountered so ...

The app.component.ts does not always trigger this function

I am looking to ensure that the following function is triggered every time a user visits my website, regardless of the URL, in order to track traffic. The site is built in Angular2 (v7). I have placed the function early on in the Angular execution stack ...

I'm having trouble getting my window resize event listener to function properly. I'm using a combination of Three.js and Vuetify.js

My goal is to incorporate a three.js renderer into a div element using the vuetify.js framework. I want my code to dynamically adjust the dimensions of the div element whenever the window is resized. I have excluded unnecessary code blocks from this excer ...

Adding a contact form to a slider: A step-by-step guide

Currently, I am faced with the challenge of placing my form on a slider in such a way that the slider appears to be running in the background of the form. When using position absolute, I find myself having to apply excessive margins and top pixels due to t ...

Triggering a JQuery click event programmatically using another click event

Below is the code snippet: <label style="display: inline; " for="default"> <img class="ful" src="http://www.mysite.com/default.png" /> <input style="display:none" id="default" name="selected" type="radio" value="template" onclick="SubmitVal ...

Using JavaScript to determine the time it will take to download something

Hi everyone, I'm a beginner in javascript and I am currently working on finding the download time of a file. I have calculated the size of the file and divided it by the current time, but unfortunately, I am not getting the correct result. This is th ...

Getting rid of an Ajax loader graphic after a period of time

After a button is clicked, I have an ajax loader that appears and here is the code snippet: jQuery(document).ready(function($) { $('#form').on('submit', function() { $('#submit').css('display', 'bl ...

Executing PHP to capture and showcase the HTTP request received from one page onto another

As a beginner in web development, I humbly ask for patience as I navigate through unfamiliar territory. If possible, please guide me through the logical steps necessary to accomplish the task at hand. I am currently working with PHP and need assistance i ...

Utilizing Google's GeoApi to retrieve users' location data regarding their city and country

I am currently using this code to retrieve the full address information of users function getGeo() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function (a) { $("#geoLoc").html("Determining your location. ...