1

Products have 4 different category. I want to show them into 3 section. How to do this with angularjs? I want to repeat ng-repeat based on product category.

Please check my 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"
  }

];
rushdi
  • 221
  • 1
  • 2
  • 14

4 Answers4

8

You can use a filter :

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

Edit : looks like everybody googled the same thig and found the same other StackOverflow answer ^^ @OP you should learn how to Google, btw !

Edit 2 : Reread the question, you need a custom filter :

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

Use it like follows :

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

Edit 3 : be aware, though, that this can be pretty expensive in terms of performances for huge arrays. If you're dealing with such arrays, I suggest pre-filtering the data into several subarrays.

LoremIpsum
  • 4,328
  • 1
  • 15
  • 17
2

You can use angular.filter module.

You will have to define your own map function in the controller:

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

then in the 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>

note that you are loosing the information on the category of the element if it is C Or D, thing that won't happen if you use LoremIpsum's answer, but with this solution you will be able to create whatever groups you want. here is a js fiddle with an example.

Daniele Sassoli
  • 899
  • 12
  • 34
1

for example <div class="" ng-repeat="item in output.products | filter: {category:'A'}"> Whould only repeat items with Category A. You could also filter with a self defined function or other criteria.

Jo Ke
  • 11
  • 1
1

You can use ng.if for this to.

Check here http://plnkr.co/edit/SKfUKTtKhUnZqec3ABSt?p=preview

  <div class="" ng-repeat="item in output.products" ng-if='item.category =="A"'>
cagica
  • 678
  • 4
  • 23