super cool
super cool

Reputation: 6045

Unable to remove item from List ?

I'm trying to remove single item from list after re-ordering but it seem to remove multiple items from list on single click .

Code:

var testApp = angular.module('testApp', ["kendo.directives"]);
testApp.controller('testController', ['$scope', function($scope) {
  $scope.mapList = [];
  $scope.addMap = function() {
    $scope.mapList.push({
      'mapNameList': [{
        'mapName': 'Test1'
      }]
    });
  };

  $scope.placeholder = function(element) {
    return element.clone().addClass("placeholder").text("drop here");
  };

  $scope.hint = function(element) {
    return element.clone().addClass("hint"); >>---- i feel issue is because of this part but not sure 
  };

  $scope.removeItem = function(data, index) {
    data.mapNameList.splice(index, 1); // it removes multiple but fires one time .
  };

  $scope.addMap = function() {
    $scope.mapList.push({
      'mapNameList': [{
        'mapName': 'Test1'
      }]
    });
  };

  $scope.addDetail = function(data) {
    data.mapNameList.push({
      'mapName': "Test"
    });
  };

}]);

Sample working fiddle here

Steps to Reproduce : //refer fiddle link

1.)click on Add Map .

2.)Now click on Add Detail for 5 times .

3.)now try reordering the records by drag and drop up & down .

4.)Click on any delete button .

Upvotes: 1

Views: 119

Answers (1)

joh04667
joh04667

Reputation: 7427

After a quick look at the kendo-sortable directive, it seems like there's an issue with inheritance and the $index variable. I don't want to sound like I know for sure what's going on since I haven't looked at the directive much, but dragging the element does not change its position (index) in the array, but the removeItem function is being called using $index and it somehow is targeting the wrong item.

Either way, I was able to fix the bug by changing line 26 on the HTML from:

<li ng-repeat="n in data.mapNameList">

to:

<li ng-repeat="n in data.mapNameList track by $index">

I think part of the issue might be because there are duplicates. The array is a list of objects though, so Angular can't track them by comparison unless you give Angular something to track them by. I think. So, deleting them when out of order can mess with how Angular is tracking them. Giving Angular something to track solves this.

Upvotes: 0

Related Questions