0

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

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

3 Comments

It's not what I'm looking for.. I want to group by the categories, not to enumerate the categories..
@Yehuda let me see if I get it right - you want to output the locations for each category?
Yes, and it need to be dynamic.. By default it's output list of locations and if the user click a button than it will output the same list but grouping by the categories

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.