ng-repeat order by number only positive value

时间:2016-09-29 11:32:19

标签: angularjs

我有一个我想根据数字排序的列表。这个数字可以是负数或正数。我的想法是从最低到最高的顺序,但数字必须是正数,负数自动隐藏。但我想添加一个选项,例如只显示正数或全部的选择器。如果您选择全部显示负面和正面但负面显示最后一个。然而,如果我只选择正面,则从最低到最高显示正面。它可以这样做吗?

<ion-item ng-repeat="torneo in torneos | orderObjectBy:'dias'" item="item" class="item item-icon-right" ng-click="verTorneo(torneo.torneo_id)">
            {{torneo.torneo_nombre}} {{torneo.dias}}
            <i class="icon ion-ios-arrow-right"></i>
</ion-item>

app.filter('orderObjectBy', function(){
return function(input, attribute) {
if (!angular.isObject(input)) return input;

var array = [];
for(var objectKey in input) {
    array.push(input[objectKey]);
}

array.sort(function(a, b){
    a = parseInt(a[attribute]);
    b = parseInt(b[attribute]);
    return a - b;
});
return array;
}
})

此功能指示数字从最低到最高,但最后无法拉负数。订单如下:

-3
-1
 2
10

我想要的是

 2
10
-1
-3

4 个答案:

答案 0 :(得分:3)

你试过吗

%time%

答案 1 :(得分:1)

尝试定义类别的排序&#34; order&#34;定义之前的人:

array.sort(function(a, b){
    a = parseInt(a[attribute]);
    b = parseInt(b[attribute]);
    var categoryA = (a < 0) 1 : 0;
    var categoryB = (b < 0) 1 : 0;
    return (categoryA == categoryB) ? a - b : categoryA - categoryB;
});

答案 2 :(得分:1)

如果你想解决这个'角度方式',你应该将输出数据的格式委托给过滤器

<ion-item
    ng-repeat="torneo in torneos | yourCustomFilter"
    ng-if="torneo.torneo_nombre > 0 || showNegatives"
    item="item"
    class="item item-icon-right"
    ng-click="verTorneo(torneo.torneo_id)">
            {{torneo.torneo_nombre}} {{torneo.dias}}
            <i class="icon ion-ios-arrow-right"></i>
</ion-item>

然后在过滤器中使用排序算法,由此问题的其他答案提供。这样,当列表更新时,将自动调用排序,并显示负数,您只需将showNegatives设置为true。

答案 3 :(得分:0)

如果负值应该显示

,你可以创建一个除了布尔符号的过滤器
app.filter("sortNegFilter", function() {
  return function(array, showNegative) {
    if(!showNegative){
        array = $filter("filter")(array, function(val){
            return val.torneo_nombre < 0;
        });
    }
    return $filter('orderBy')(array, 'torneo_nombre');
  };
});

然后将bool绑定到您的视图,选中时showNeg将为true

<label><input type="checkbox" ng-checked="showNeg"> Show negative numbers </label>
<ion-item ng-repeat="torneo in torneos | sortNegFilter:showNeg" item="item" class="item item-icon-right" ng-click="verTorneo(torneo.torneo_id)">
    {{torneo.torneo_nombre}} {{torneo.dias}}
    <i class="icon ion-ios-arrow-right"></i>
</ion-item>