Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
613 views
in Technique[技术] by (71.8m points)

sorting - Angularjs wrong $index after orderBy

I am new to Angular.js and have some problems sorting my array and working on that sorted data.

I have a list with items and want so sort it by "Store.storeName", which is working so far. But after sorting the data, my delete-function is not working anymore. I think thats because the $index is wrong after sorting, and so the wrong data is deleted.

How can I solve that? Ordering the data in the scope and not in the view? How to do that?

Here is some relevant code:

In the View:

<tr ng-repeat="item in items | orderBy:'Store.storeName'">
                <td><input class="toggle" type="checkbox" ng-model="item.Completed"></td>
                <td>{{item.Name}}</td>
                <td>{{item.Quantity}} Stk.</td>
                <td>{{item.Price || 0 | number:2}} €</td>                
                <td>{{item.Quantity*item.Price|| 0 | number:2}} €</td>
                <td>{{item.Store.storeName}}</td> 
                <td><a><img src="img/delete.png" ng-click="removeItem($index)">{{$index}}</a></td>
            </tr>

And in my controller I have this delete function, which should delete the specific data:

$scope.removeItem = function(index){
        $scope.items.splice(index,1);
    }

This works nicely before ordering in the View. If something important is missing, please let me now.

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Instead or relaying on the $index - which - as you have noticed - will point to the index in a sorted / filtered array, you can pass the item itself to your removeItem function:

<a><img src="img/delete.png" ng-click="removeItem(item)">{{$index}}</a>

and modify the removeItem function to find an index using the indexOf method of an array as follows:

$scope.removeItem = function(item){
   $scope.items.splice($scope.items.indexOf(item),1);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...