Compare array value after sorting angular js
This is a problem that extends from Click Returns an invalid pointer 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 is trying to remove an item in the array after sorting that "$ index" will not return the correct index, so the solution suggested passing "item" directly as a parameter and using "indexof (item)".
My question is, 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 cannot compare the value of item.Price between the first and second elements of the sorted array .
What's the best approach?
+3
source to share
1 answer
You can use a custom one $filter
, something like this:
.filter('prevExpression', function($parse){
return function(prevItemExpression){
if(!prevItemExpression || !this.$$prevSibling)
return undefined;
return $parse(prevItemExpression)(this.$$prevSibling);
}
})
An example for such a controller:
.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 can do it:
<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
+1
source to share