Search code examples
javascriptjqueryangularjsdragula

Angular Sorting and counting, Dragula


I have the following scenario:

A JSON object array gets fetched with angular ajax and displayed as list with ng-repeat. The list gets sorted by object property "index", which is set as default input value of the respective list item.

The user can change the input values. On press of a button, the list gets redrawn, sorted by the updated input values. Now there should be a counter, ++ whenever a list item changes position.

I so far managed to count all list items with updated values. How do I register position changes for the other list items that change position?

For example: #3 changes position to #1, then #1 and #2 also change position.

Second, using Dragula, the list items are now draggable. How can I resort the list after list items were dragged?

I also tired Angular Dragula without success.

here is my code on github.

Thank you for your help!


Solution

  • I had a similar issue. You need a way of getting the DOM indexing and updating the JavaScript object to match. I looped through the DOM elements, got their index values, found the corresponding item in the data object and then set the index value in the object to that of the DOM index value. Hope this example helps someone.

    var updateIndexes = function() {
    
      // this gets the index of any DOM element, like jQuery index()
      function getIndex(el) {
        for (var i = 0; el = el.previousElementSibling; i++);
        return i;
      }
    
      // loop through the list DOM elements
      for (var i = 0; i < dataArray.length; i++) {
        var dataId = dataArray[i].id;
        var domIndex = getIndex(document.getElementById(dataId));
        dataArray[i].index= domIndex;
      }
    
    };