Is it possible for ng-repeat to change the index of an internal collection while reordering?

In my code, I am working with an array of objects:

$scope.widgets = [{
    col: 0,
    name: "Tile 1"
}, {
    col: 1,
    name: "Tile 2"
}, {
    col: 2,
    name: "Tile 3"
}];

Each object from the array is displayed as a widget within a grid. When using ng-repeat, a new widget is created in its respective position (col, row) for each iteration:

    <li gridster-item="widget" ng-repeat="widget in widgets">

While testing, I noticed that when objects are reordered, their properties in terms of position (col/row) are updated via two-way binding. However, the objects themselves do not change positions in the array based on their new order. For example, if the user switches tile 1 (index 0) and tile 2 (index 1), the properties are updated but the objects remain in the same positions within the array.

You can view a demo of this behavior here, where the 'row' and 'col' properties change as tiles are moved around the grid, but the index stays the same. Is it possible to reorganize the collection to reflect the current position of the ng-repeat item?

For example, if a user drags tile 2 to the position of tile 1, tile 2 should become index 0 and tile 1 should become index 1;

Answer №1

To ensure your widgets array is sorted after dragging, it's essential to define a callback function for that purpose.

I've made changes to your jsFiddle with the complete solution, but here are the key points:

Set up the drag callback

Include the following code in your gridster options:

draggable: {
    enabled: true,
    stop: function (event, $element, widget) {
        sortWidgets();
    }
}

Implement the sorting logic

If you're using underscore or lodash, the .sortBy() function can simplify this task. Alternatively, you can achieve this using native JavaScript as shown below:

function sortWidgets() {
    $scope.widgets.sort(function (widget1, widget2) {
        return position(widget1) - position(widget2);
    });
}

function position(widget) {
    return (widget.row || 0) * $scope.gridConfig.columns + widget.col;
}

Optimize ng-repeat with track by

If your widgets are complex, consider adding a track by expression to ng-repeat. This will enhance performance by reusing the same DOM node for a widget after sorting, rather than creating a new one. It's a small optimization that can prevent performance issues in the future.

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

Steps for setting the value of a textbox within a bootstrap popover

When a user clicks on an Anchor element, I am displaying a Bootstrap popover using the following JQuery code. Jquery $("[data-toggle=popover]").popover({ trigger: 'click', placement: "top", html: true, ...

The system is unable to accept the Object ID

I am encountering an issue with displaying the Object ID from MongoDB in the console in VS Code. I am trying to retrieve the Object ID for the user who is currently logged into my application. I have created a hidden input tag with an id of ObjectID. <! ...

What methods are most effective for evaluating the properties you send to offspring elements?

Currently, I'm in the process of testing a component using Vue test utils and Jest. I'm curious about the most effective method to verify that the correct values are being passed to child components through their props. Specifically, I want to e ...

Sharing JSON data with public/javascripts/X.js in Node/Express: A beginner's guide

Currently facing a challenge with my Express project. Take a look at https://github.com/MoreeZ/help1 and examine ./public/javascripts/budget.js. My goal is to swap the incomeData object to read data from ./incomedata.json I attempted passing it through th ...

Steer clear of using inline styling when designing with Mui V5

I firmly believe that separating styling from code enhances the clarity and cleanliness of the code. Personally, I have always viewed using inline styling (style={{}}) as a bad practice. In Mui V4, it was simple - I would create a styles file and import i ...

locate and interact with a dynamically created button using JavaScript through ajax

Hey there, I'm trying to display an image along with a button using AJAX whenever a visitor uploads an image. for (var i = 0; i < data.length; i = i + 1) { imageThump += '<img src="' + data[i].path + '" />'; image ...

Ways to merge values across multiple arrays

There is a method to retrieve all unique properties from an array, demonstrated by the following code: var people = [{ "name": "John", "age": 30 }, { "name": "Anna", "job": true }, { "name": "Peter", "age": 35 }]; var result = []; people. ...

Is it possible to view the list of errors displayed by vscode when opening a JS file exclusively through the terminal?

Is there a default configuration file that vscode uses to display errors and warnings? I want to identify all issues in my JavaScript project. I don't have any jsconfig.json or tsconfig.json files, only using the //@ts-check directive in some files. ...

Reactive forms in Angular now support changing focus when the Enter key is pressed

I have successfully created a table and a button that generates dynamic rows with inputs inside the table. One issue I'm facing is that when I press enter in the first input, a new row is created (which works), but I can't seem to focus on the ne ...

What could be causing the issue of not being able to access an element visible in AngularJS Videogular?

I am currently working on integrating the videogular-subtitle-plugin with the most recent version of Videogular/AngularJS. As a newcomer to AngularJS, I believe there must be a simple solution that I am overlooking. My main challenge lies within a directi ...

Adjust the path-clip to properly fill the SVG

Is there a way to adjust the clip-path registration so that the line fills correctly along its path instead of top to bottom? Refer to the screenshots for an example. You can view the entire SVG and see how the animation works on codepen, where it is contr ...

Displaying the state in NextJS rather than revealing server error messages

I recently implemented a register page on my NextJS app where users can input their information. Once the registration is successful, the form clears and a success message is displayed. However, I encountered an issue after adding the success message. Now ...

Ensure that the input remains below ten

My goal here is to ensure that the value in an input element is a non-zero digit (0<x<=9). Here's the HTML tag I'm using: <input type="number" class="cell"> I've experimented with various JavaScript solutions, but so far none h ...

When the onClick event is triggered, my intention is to dynamically insert a new

I'm having trouble adding a new row on each click, as my code keeps replacing the existing row. I attempted moving the if statement outside the addTable function, but it didn't work as expected. I've tried multiple solutions without succes ...

Display information from a selected card on a separate page upon clicking

I am currently working with a JSON file to display cards on a webpage. The code is sourced from a file named paintings.js and the cards are rendering correctly. However, when I click on a card, it redirects me to a blank paintingInfo.js page. I'm wond ...

When state is updated, the component is re-rendered multiple times

I am working on setting the state in componentDidMount lifecycle method to verify data from local storage. Depending on whether the data exists in local storage, I either redirect the user to the login page or keep them on the dashboard. Is there a way to ...

What is the process for transitioning data between SQL, PHP, and JavaScript seamlessly?

As a developer who frequently works on SQL/PHP applications, I often find myself constantly rewriting JavaScript code to accomplish the same tasks repeatedly. When dealing with simple APIs, it's not too difficult to create one-off AJAX methods to comm ...

Tips for updating partial views when the appCache is refreshed

I am currently implementing angularjs routing: angular.module('questionModule', []). config(['$routeProvider', function ($routeProvider) { $routeProvider. when('/questions', { templateUrl: 'partials/questio ...

Tips for adjusting the dimensions of material table within a react application

Could someone please provide guidance on adjusting the size of a table made with material table? I am currently working in React and the following code is not yielding the desired outcome. I even attempted to use 'react-virtualized-auto-sizer' wi ...

Extract the links from the database using AngularJS

Currently, I am utilizing Laravel 5 for the backend and Angular.js for the frontend. The application operates solely through ajax requests. In my view, I have static links that are always visible on any page. Here is an example of how they are displayed: ...