简体   繁体   中英

AngularJS - Group by array

I have a scope array of locations, each location can be in one or more categories.
For eaxmple:

Locations: [{id: 1,
  name: "NJ",
  categories: [0, 2, 3]
},{
  id: 2,
  name: "NY",
  categories: [0, 2]
}]

Categories: [{
  id: 0,
  name: "Cities"
}, {
  id: 2,
  name: "Canyons"
}, {
  id: 3,
  name: "Work"
}]

In my app I display all of the locations with this code:

<div ng-repeat="row in rows">
    {{ row.name }}<br>
    Categories: <span enum-categories="row"></span>
</div>

Now I want to add the option to group the items by their categories..
My problem is that each item can have more than one category..

The result need to be something like this:

cat 0:
NJ, NY

cat 1:
Nothing

cat 2:
NJ, NY

cat 3:
NJ

How can I do this?
Thank you :)

This custom filter does what you need

app.filter('locByCatFilter', function() {
  return function(locations, catId) {
    if (!locations || !catId) {
      return;
    }
    return locations.filter(function(loc) {
      return loc.categories.indexOf(catId) > -1;
    });
  }
})

Usage:

<ul>
  <li ng-repeat ="cat in Categories">
      Category: {{cat.name}}
      <ul>
        <li ng-repeat="loc in filteredLoc =(Locations | locByCatFilter:cat.id)">
          {{loc.name}}
        </li>
        <li ng-if="!filteredLoc.length">None</li>
      </ul>
  </li>
</ul>

If you wanted to use groupBy you would need to map your data first and create duplicates I believe

DEMO

Awkay, what you need to do is a custom filter:

<div ng-repeat="category in categories">
    {{ category.id }}<br>
    Locations: 
  <span enum-categories="row" 
    ng-repeat="location in filteredLocations =
                (locations | filter:hasCategory(category.id))">

    {{ location.name }}
  </span>
  <p ng-hide="filteredLocations.length">Nothing</p>
</div>

And in your JS:

yourModule.filter('hasCategory', function(){
    return function(location, categoryId) {
        if(location.categories.indexOf(categoryId) != -1) {
          return location;
        }
    };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM