Optimizing AngularJS ng-repeat for better performance

Currently, I am in the process of developing a basic app using AngularJS. The application initiates an asynchronous AJAX call to the server, which responds with an array structured as follows:

{
    paragraphs: [
        {content: "content one"},
        {content: "cnt two"},
        {content: "random three"},
        {content: "last one yeeaah"}
    ]
}

Subsequently, I am assigning this content to the StorageService factory through the set method, and everything appears to be functioning correctly here.

In order to display the results, I have implemented the ng-repeat directive, along with integrating JQuery UI sortable to enable the reordering of elements. Upon swapping items, my script calls the StorageService.swap method to update the element order in StorageService. However, despite the changes being reflected in StorageService, ng-repeat fails to rerender the modified sequence. Oddly enough, removal, addition, or modification of content triggers the desired result. How can I compel Angular to refresh and rerender ng-repeat?

= JSFIDDLE =

http://jsfiddle.net/6Jzx4/3/

= Example =

Following a swap event, ng-repeat should automatically update to ensure consecutive IDs.

= Code =

HTML

<div ng-controller="Test" sortable>
    <div ng-repeat="item in data().paragraphs" class="box slide_content" id="{{$index}}"> 
        {{item.content}}, ID: {{$index}}
    </div>

    <input type="button" ng-click="add()" value="Add">
</div>

JS

var App = angular.module("MyApp", []);

App.controller("Test", function($scope, StorageService) {
    StorageService.set({
        paragraphs: [
            {content: "content one"},
            {content: "cnt two"},
            {content: "random three"},
            {content: "last one yeeaah"}
        ]
    });

    $scope.data = StorageService.get;

    $scope.add = StorageService.add;
});

App.directive("sortable", function(StorageService) {
    return {
        link: function(scope, element, attrs) {
            $(element[0]).sortable({
                cancel: ".disabled",
                items: "> .slide_content:not(.disabled)",
                start: function(e, t) {
                    t.item.data("start_pos", t.item.index());
                },
                stop: function(e, t) {
                    var r = t.item.data("start_pos");
                    if (r != t.item.index()) {
                                    StorageService.sort($(this).sortable("toArray"));
                    }
                }
            });
        }
    };
});

App.factory('StorageService', function() {
    var output = {};

    return {
        set: function(data) {
            angular.copy(data, output);
            return output;
        },
        get: function() {
            return output;
        },
        add: function() {
            output.paragraphs.push({
                content: 'Content'
            });
        },
        sort: function(order) {
            var localOutput = [];

            for (var j in order) {
                var id = parseInt(order[j]);
                localOutput.push(output.paragraphs[id]);
            }

            console.log('new order', localOutput);

            output.paragraphs = localOutput;
            return output;
        }
    };
});

Answer №1

When working with Angular, keep in mind that the framework may not detect changes you make to an array. To ensure your sort is recognized, include it within a `scope.$apply()` function.

It's important to note that using a `that` variable can help maintain consistency, as the context of `this` can shift inside the `apply`.

var that = this;
scope.$apply(function() {   
   StorageService.sort($(that).sortable("toArray"));
}

However, implementing this fix may reveal other issues stemming from the interplay between jQuery sortable and Angular (you can see an example in this fiddle). These challenges have been resolved in Angular UI Sortable, suggesting a beneficial approach for moving forward.

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

How to insert an element INTO a JSON array using JavaScript

I'm having an issue with the way a line is displayed on my screen: Would you like to pay €xx to POS_ID Latte X 1....€2.50-Salad X 1....€4.00-Wrap X 1....€4.50-Coffee X 2....€3.00- My desired format is as follows: Would you like to pay ...

Guidelines on redirecting after submission

Looking for assistance with a code I have - I need to redirect the submitter to a specific page after the form data is submitted. If you try out the code at this link "http://www.w3schools.com/html/tryit.asp?filename=tryhtml_default" and follow the instru ...

javascript variable pointing to an unknown object

Below is the essential code snippet to consider: JS function ToggleRow(objTwistie, objRow) { if (objRow.style.display == "none") { objRow.style.display = ""; objTwistie.src = "../Images/SectionDown.gif"; } else { objRow.style.display = "n ...

Having trouble with the product filter in Mongoose, unable to retrieve products

const mongoose = require("mongoose"); const { ObjectId } = mongoose.Schema; const productSchema = new mongoose.Schema( { title: { type: String, trim: true, required: true, maxlength: 32, text: true, }, ...

The ng-controller is not functioning properly even when being correctly invoked

I tried out some simple angularjs code, utilizing nodejs, angularjs, and html. Here are my files: https://github.com/internial/test. I decided not to include the node_modules folder as it was too large. On localhost:8080, this is the result: {{1 + 64}} ...

What could be the reason for this JSON being considered "invalid"?

Despite passing validation on jsonlint, both Firefox and Chrome are rejecting this JSON: { "messages": [ { "subject": "One" }, { "subject": "Two" }, { "subject": "Three" ...

When an object is passed through JSON.stringify, the resulting output is simply an

My attempt to convert a JavaScript object into JSON is not working as expected. When I use console.log(myObject), the object is displayed correctly. However, when I try console.log(JSON.stringify(myObject));, I only get an empty object {}. Can anyone poi ...

Managing Firebase authentication with ui-router

I'm currently working on integrating Firebase authentication with routers (ui-router) following the example provided here. My goal is to allow access to multiple pages without requiring authentication. However, I'm facing an issue when a signed- ...

Error: ChunkLoadError - Unable to load chunk for node_modules_next_dist_client_dev_noop_js

As I was working through the basics tutorial on the Next.js website, I encountered an issue when reaching the Global Styles step. The runtime error that started appearing is as follows: ChunkLoadError: Loading chunk node_modules_next_dist_client_dev_noop_j ...

Unit testing an API built with Express and Mongoose using Jest

I have decided to implement a TDD approach for a user API that I am working on. Specifically, I am looking to add unit tests for two functions: userRegister and userLogin. Here is the code snippet from my app.js: 'use strict' const express = r ...

The cancel button is experiencing unexpected behavior when used in conjunction with the jQuery load event

I'm experiencing an issue with a cancel button on my website. After clicking the cancel button, it cancels the action but then proceeds to reload the page. I attempted to fix this by adding the "preventDefault" method, but it did not resolve the iss ...

Hiding Div with JavaScript (Quick and Easy)

Hey there, I'm looking to make regStart and regPage alternate visibility based on a click event. I'm still getting the hang of JavaScript so any simple answers would be appreciated. <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/x ...

Prettier eliminates the need for parentheses in mathematical expressions

When working with mathematical expressions in React and attempting to slice an array based on those expressions, I encountered an issue with the Prettier extension. It automatically removes parentheses from the expressions, resulting in incorrect calculati ...

The AngularJS framework does not recognize the _spPageContextInfo variable

I have recently embarked on the journey of integrating userName with AngularJs into SharePoint. My goal is to be able to retrieve and display all userNames from a SharePoint list. However, I keep encountering an error message that states '_spPageConte ...

Altering the hover functionality for dynamically created class elements

I have a vision to create a unique e-commerce storefront with tile design, featuring an item thumbnail that reveals the item name upon hovering. I found inspiration from this example, but I want the item name to slide up smoothly on hover, rather than simp ...

Allow-Origin Headers for Gas Access

When attempting to send an (HTTP GET) $.ajax request from jsfiddle to my Google Apps Script server, I encountered the following error: XMLHttpRequest cannot load https://script.google.com/macros/s/mykey?params. Origin http://fiddle.jshell.net is not allow ...

What is the best way to populate a remote html page in real-time according to user input?

Is it feasible to use only JavaScript and HTML to allow users to select from a list of options and then print a page that includes a checklist of their selections? ...

AngularJS compatibility with Internet Explorer 9

Encountering a minor issue with AngularJS and Internet Explorer 9. It seems like AngularJS is not loading correctly. When I open IE with my application, nothing functions properly. However, if I launch the development tools of IE9 and refresh the page, my ...

Refreshing the page causes JavaScript to fail loading

Recently, I encountered a puzzling error. Upon visiting this link The carousel fails to load properly near the bottom of the page. However, if you click on the logo or navigate back to the home page, it works fine. Additionally, performing a command + r ...

How can I make this NextJS component show its width as soon as the page loads?

When I try to run this code to retrieve the browser's screen width, I encounter the following error: ReferenceError: window is not defined The commented-out code works fine with a default value of 0 and updates correctly when the browser width chan ...