deleting an element in ng-repeat with orderBy and

2019-09-11 23:12发布

问题:

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