2

I have a JSON feed that looks something like this:

[{
    "title":"Post 1",
    "categories":[1]
},{
    "title":"Post 2",
    "categories":[12,123]
},{
    "title":"Post 3",
    "categories":[123]
}]

and I'd like to be able to filter it by "categories" and "title", like so:

<select ng-model="search.categories">
    <option value="">Categories</option>
    <option value="1">1</option>
    <option value="12">12</option>
    <option value="123">123</option>
</select>

<input ng-model="search.title">

<ul>
    <li ng-repeat="post in posts | filter:search">
        {{post.title}} - {{post.categories}}
    </li>
</ul>

Title search works fine. But for categories a search for "1" matches "1", "12" and "123" (and similarly, "12" matches "12" and "123"). Is there a way to limit search results to the exact match? I'm assuming to do that "categories" array has to be split somehow so each ID is matched separately.


Another option: can I filter parent loop based on content of nested child loop? Here's the code:

<ul>
    <li ng-repeat="post in posts | filter:search">
        {{post.title}}
        <ul>
            <li ng-repeat="category in post.categories">
                {{category}}
            </li>
        </ul>
    </li>
</ul>

1 Answers1

0

You can add a comparison function or simply true after another colon, to have angular only accept exact matches. Also you can use multiple filters by just adding another pipe. It should look something like this:

<li ng-repeat="post in posts | filter : search.categories : true | filter : search.title">

See more here: https://docs.angularjs.org/api/ng/filter/filter

Luka Jacobowitz
  • 22,795
  • 5
  • 39
  • 57
  • Exact filter doesn't work as is because I'm comparing a single value to a comma separated array. If I were to search for "1", posts with "categories" set to "1,12,123" won't match. – user5050800 Mar 25 '16 at 20:17