问题描述:

This is a problem that extended from Click Return wrong Index after Sorting !

 > <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(item)">{{$index}}</a></td>

So in his question he try to remove the item in the array after sorting, which "$index" wouldn't return the correct index, so the solution suggested to pass back "item" itself as a parameter and use "indexof(item)" function.

My question is what if I want to compare the value after sorting?


Since the $index does not reflect the actual sorted index in the new sort array I cant not compare calculate the value of item.Price between the first item and second item in the sorted array.

What is the best approach?

网友答案:

You could use a custom $filter, something like this:

.filter('prevExpression', function($parse){
    return function(prevItemExpression){
        if(!prevItemExpression || !this.$$prevSibling)
            return undefined;        
        return $parse(prevItemExpression)(this.$$prevSibling);
    } 
})

For Example for a controller like this:

.controller('testController', function($scope){
    $scope.items = [
        {id:1, name:'a', price:12.5},
        {id:2, name:'b', price:0.5},
        {id:3, name:'c', price:1.5},
        {id:4, name:'d', price:8},
        {id:5, name:'e', price:100}
    ];

})

You could do this:

<table ng-app="testApp" ng-controller="testController">
    <tr>
        <td>Name</td>
        <td>Price</td>
        <td>Prev Item Price</td>        
    </tr>
    <tr ng-repeat="item in items | orderBy:'price'">
        <td>{{item.name}}</td>
        <td>{{item.price}}</td>
        <td>{{'item.price' | prevExpression }}</td>        
    </tr>
</table>

Example

相关阅读:
Top