2016-09-29 67 views
0

我有一個列表,我想根據數字進行排序。這個數字可以是負數也可以是正數。我的想法是,從最低到最高的順序,但數量必須是正數,負數自動隱藏。但是我想添加一個選項,例如只顯示正值或全部的選擇器。如果選擇全部同時顯示負數和正數,但對最後一個顯示負數。而如果我只選擇正數,則從最低到最高顯示正數。它可以做到這一點?ng-repeat number by number only positive

<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 
+0

對不起,我更新了@thepio – sioesi

+0

您可以請創建小提琴 –

回答

3

你有沒有試過

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

哪裏定義的排序?控制器? – sioesi

+1

它更好地分享小提琴來更好地理解它 – Tester

+0

未捕獲的SyntaxError:意外的數字這個錯誤 – sioesi

1

嘗試一種定義類別「命令」定義之前,誰上臺:

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; 
}); 
+0

那個數組是我的torneos? – sioesi

+0

我的問題是,我在哪裏定義.Sort – sioesi

1

如果您想solv e這種'角度的方式'你應該把輸出數據的格式分配給過濾器

<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即可自動調用排序。

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'); 
    }; 
}); 

然後布爾綁定到你的觀點,當檢查showNeg將是真正的

<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>