Reputation: 1818
How can I use a method with orderBy ?
I would like to sort my array from ng-repeat with a method and not a property :
index.html
<tbody>
<tr ng-repeat="product in results.data | orderBy: product.getAllCounter()">
<!-- Product name -->
<td ng-bind="(product.product_offer[0].app_name === null) ? product.app.store_id : product.product_offer[0].app_name"></td>
<!-- Counter -->
<td class="text-right" ng-bind="product.getAllCounter()"></td>
<!-- Action -->
<td class="text-center">
<div class="btn-group">
<a ng-href="/#/product/{{ product.id }}" type="button" class="btn btn-default btn-sm">
See
</a>
</div>
</td>
</tr>
</tbody>
Product.prototype.getAllCounter
// Return result all counter in promo
Product.prototype.getAllCounter = function () {
var sum = 0;
angular.forEach(this.product_promo_linker, function (product_promo_linker) {
sum += product_promo_linker.promo.count;
});
return sum;
};
I tried with
orderBy: product.getAllCounter()
and
orderBy: product.getAllCounter
The method product.getAllCounter return integer
SOLVED
I used :
<tr ng-repeat="campaign in results.data | orderBy: getAllCounter:true">
in my controller.js :
$scope.getCounter = function(product) {
return campaign.getAllCounter();
};
Upvotes: 1
Views: 101
Reputation: 7438
Just pass reference
angular.module('app', [])
.controller('ctrl', function($scope) {
$scope.products = [{
name: 'foo',
age: 2
}, {
name: 'bar',
age: 1
}, {
name: 'baz',
age: 3
}]
$scope.orderByAge = function(element) {
return element.age
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<ul ng-app='app' ng-controller='ctrl'>
<li ng-repeat="product in products | orderBy: orderByAge">
{{ product.name }} - {{ product.age }}
</li>
</ul>
Upvotes: 0
Reputation: 193261
If you want to use custom ordering function then you need to provide one:
ng-repeat="product in results.data | orderBy: product.getAllCounter"
Note: no ()
after function name: you want to use function reference, not result of function invocation.
Upvotes: 1