deleting an element in ng-repeat with orderBy and

2019-09-11 23:21发布

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)"

4条回答
beautiful°
2楼-- · 2019-09-11 23:54

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楼-- · 2019-09-11 23:56

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

查看更多
在下西门庆
4楼-- · 2019-09-11 23:57

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

查看更多
\"骚年 ilove
5楼-- · 2019-09-12 00:12

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>
查看更多
登录 后发表回答