deleting an element in ng-repeat with orderBy and track by is failing

主宰稳场 提交于 2019-12-13 05:58:19

问题


Here is the code

<tr ng-repeat="collection in collections | orderBy:'-modifiedDate' track by $index" ng-init="listIndex = $index">

If I remove orderBy:'-modifiedDate', the deletion on a specific element is working great. However, I need the collection/array to be rendered in sorted way that's why I have orderBy.

If I don't delete the orderBy:'-modifiedDate' from the code and I delete a random element say on position 7, the element that gets deleted is the very last always.

I had to use ng-init since I have another ng-repeat inside the ng-repeat shown above. I call the delete function like this, ng-click="deleteRow(listIndex)"


回答1:


alert listIndex in the deleteRow method, if it is coming correct as 7, use splice(listIndex,1) to do the deletion.




回答2:


This is how I got it to work.

in the template

<tr ng-repeat="collection in collections| orderBy:'-modifiedDate'">
 ........
 ... there is another ng-repeat here
   <a ng-click="deleteItem(collection)">Delete this item</a>

in the controller

  $scope.deleteItem = function(item) {
      $scope.collections.splice($scope.collections.indexOf(item), 1);
  }



回答3:


Or, even more simple:

$scope.deleteItem = function(array, index){
   array.splice(index, 1);
};

And in your html:

<tr ng-repeat="collection in collections| orderBy:'-modifiedDate'">
 ..........
 ..........
 <a ng-click="deleteItem(collections, $index)">Delete this item</a>



回答4:


When you use orderBy, angular creates another "collections" in the scope, and changes the order of its elements, but the original "collections" stays the same, for example if :

    $scope.collections = [
    { name: '1st element', id: '1' },
    { name: '2nd element', id: '2' },
    { name: '3rd element', id: '3' }
];

<tr ng-repeat="collection in collections | orderBy:'id':true track by $index">

$scope.collections[2] would still be { name: '3rd element', id: '3' }

Here's what you can do, you can give a name to that sorted collection created by angular :

<tr ng-repeat="collection in sortedCollections = (collections | orderBy:'id':true) track by $index">

And then you could use $scope.sortedCollections[2] instead



来源:https://stackoverflow.com/questions/31803304/deleting-an-element-in-ng-repeat-with-orderby-and-track-by-is-failing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!