0

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

manoj
  • 3,391
  • 2
  • 20
  • 30
devwannabe
  • 3,160
  • 8
  • 42
  • 79

4 Answers4

0

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

manoj
  • 3,391
  • 2
  • 20
  • 30
  • 1
    I'm so sorry, I just found a better way and it's working great now. This is the code I'm using now $scope.collections.splice($scope.collections.indexOf(item), 1); I got rid of the track by and listIndex too – devwannabe Aug 04 '15 at 07:46
  • Thank you. I posted my answer since I cannot format the one in the comment :) – devwannabe Aug 04 '15 at 07:52
0

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);
  }
devwannabe
  • 3,160
  • 8
  • 42
  • 79
0

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>
manoj
  • 3,391
  • 2
  • 20
  • 30
Razvan B.
  • 6,721
  • 2
  • 19
  • 32
  • That's the code I had earlier but with the presence of orderBy and track by, it deletes the last row even if the index is correct. – devwannabe Aug 04 '15 at 13:59
0

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

hmk
  • 139
  • 1
  • 5