在ng repeat中使用带有orderBy的方法

Use method with orderBy in ng-repeat

本文关键字:orderBy 方法 ng repeat      更新时间:2023-09-26

如何将方法与orderBy一起使用?

我想用一个方法而不是一个属性对我的数组进行排序:

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>

产品原型.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;
};

我试过

orderBy:product.getAllCounter()

订购人:product.getAllCounter

方法product.getAllCounter返回整数

已解决

我用过:

<tr ng-repeat="campaign in results.data | orderBy: getAllCounter:true">

在我的控制器js:

$scope.getCounter = function(product) {
    return campaign.getAllCounter();
};

如果你想使用自定义排序功能,那么你需要提供一个:

ng-repeat="product in results.data | orderBy: product.getAllCounter"

注意:函数名称后没有():您希望使用函数引用,而不是函数调用的结果。

只需通过引用

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>