簡體   English   中英

有條件的角度ng重復

[英]angular ng-repeat with condition

產品有4個不同的類別。 我想將它們分為3部分。 如何用angularjs做到這一點? 我想根據產品類別重復ng-repeat。

請檢查我的plnkr: http ://plnkr.co/edit/XdB2tv03RvYLrUsXFRbw?p=preview

var product = [

  {
    "name": "Item 1",
    "dimension": {
      "height": "4 in",
      "width": "3 in"
    },
    "category": "A"
  }, {
    "name": "Item 2",
    "dimension": {
      "height": "2 in",
      "width": "6 in"
    },
    "category": "B"
  }, {
    "name": "Item 3",
    "dimension": {
      "height": "2 in",
      "width": "3 in"
    },
    "category": "C"
  }, {
    "name": "Item 4",
    "dimension": {
      "height": "5 in",
      "width": "2 in"
    },
    "category": "D"
  }

];

您可以使用過濾器:

ng-repeat="item in output.products | filter:{ category: 'A'}"

編輯 :好像每個人都用谷歌搜索相同的thig並找到相同的其他StackOverflow答案^^ @OP,應該學會如何使用Google,順便說一句!

編輯2 :重新閱讀問題,您需要一個自定義過濾器:

app.filter('category', function() {
  return function(items, categories) {
    if (!items || items.length === 0) {
      return [];
    }

    return items.filter(function(item) {
      return categories.indexOf(item.category) > -1;
    });
  };
});

如下使用它:

ng-repeat="item in output.products | category:['A', 'B']"

編輯3 :但是請注意,就大型陣列的性能而言,這可能會非常昂貴。 如果要處理此類數組,建議將數據預先過濾為幾個子數組。

您可以使用angular.filter模塊。

您將必須在控制器中定義自己的map函數:

$scope.group = function(elem){
    if(elem.category == 'C' || elem.category=='D'){
       elem.category = 'C OR D' ;
       return elem;
    }
    else return elem;
}

然后在HTML

<ul ng-repeat="(key, value) in products | map: group | groupBy: 'category'">
  Group name: {{ key }}
  <li ng-repeat="product in value">
     player: {{ product.name }} 
  </li>
</ul>

請注意,如果元素是C或D,則會丟失元素類別的信息,如果使用LoremIpsum的答案就不會發生這種情況,但是使用此解決方案,您將能夠創建所需的任何組。 這是一個帶有示例的js小提琴

例如<div class="" ng-repeat="item in output.products | filter: {category:'A'}">誰只能重復類別A的項目。您還可以使用自定義函數或其他條件進行過濾。

您可以為此使用ng.if。

在這里檢查http://plnkr.co/edit/SKfUKTtKhUnZqec3ABSt?p=preview

  <div class="" ng-repeat="item in output.products" ng-if='item.category =="A"'>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM