0

I'm trying to implement an AngularJS plugin into my application, but I can't really get it to work properly. I might be doing something wrong.

I have two panels that are sortable. I can swap their positions only once. After that they won't swap places anymore.

Here is an example of my problem: http://plnkr.co/edit/44fN6h6VyIft7j7bvs4j?p=preview

Anyone any idea what the problem is and how I can fix this issue?


Plnkr code (complete code in example):

<button type="button" ng-click="addItem('item1.html');">Add item 1</button>
<button type="button" ng-click="addItem('item2.html');">Add item 2</button>

<div ui-tree class="dd">
    <ol ui-tree-nodes ng-model="list.items" class="dd-list">

        <li ui-tree-node class="dd-item dd3-item" ng-repeat="element in list.items track by $index">
            <div class="panel panel-default">
                <div class="panel-heading clearfix">
                  Heading
                </div>
                <div id="settings-body{{$index}}" class="panel-body" data-nodrag>
                    <ng-include src="element.name"></ng-include>
                </div>
            </div>
        </li>

    </ol>
</div>

App.js

var app = angular.module('plunker', ['ui.tree']);

app.controller('MainCtrl', function($scope) {
  $scope.list = {};
  $scope.list.items = [];

  $scope.addItem = function(name) {
    $scope.list.items.push({name: name});
  }
});
Vivendi
  • 20,047
  • 25
  • 121
  • 196

2 Answers2

0

Its normal, you are trying to sort the list by index which sorts it each and every time when loops runs, no matter how many times you swap the div, it will end up with sorted list by index.

Remove "track by $index" from the ng-repeat on li tag and it will work.

Note: "You should use "track by $index" only when you are maintaining indexes on your back end."

Dinesh Nagar
  • 768
  • 2
  • 11
  • 23
0

You have to reference the parent and index while using angular-ui-tree.

Simply change your ng-repeat="element in list.items track by $index to ng-repeat="element in list.items track by $id(element)"> That's it ;)

Working solution here: http://plnkr.co/edit/K9duKVxNP6jCOlfuVPSQ?p=preview

julien bouteloup
  • 3,022
  • 22
  • 16