4

I've just started playing with Angular, and I'm having a hard time understanding certain things here. I wanted to set up a list of products, which belong to different categories. Some products are in the same category, like so :

$scope.products = [
  {'name': 'Product 1', 'cat':'Cat 1'},
  {'name': 'Product 2', 'cat':'Cat 2'},
  {'name': 'Product 3', 'cat':'Cat 2'},
  {'name': 'Product 4', 'cat':'Cat 3'},
  {'name': 'Product 5', 'cat':'Cat 3'},
  {'name': 'Product 6', 'cat':'Cat 2'},
];

I was able to create a <select> which merges the same categories in order to avoid duplicates, thanks to the unique filter from AngularUI. Here is the code :

<select ng-model="query" ng-options="c.cat for c in products | unique:'cat'">
    <option value="0">Default</option>
</select>

<ul>
    <li ng-repeat="c in products | filter:query">
        {{c.name}}
    </li>
</ul>

I want to display the results in a list according to the category I've selected. But when I try to do so, the only product returned in the list will be the first one inside the category. I've created a Fiddle with my problem: http://jsfiddle.net/F7Hvq/3/.

Any help would be really appreciated!

1 Answer 1

5

Here are some mistakes:

  • The <select> will choose the entire product. So | filter:query will keep the thing that matches the product, i.e. the first product of the category in the array. I'd suggest you write it as:

    <select ng-model="query" ng-options="c.cat as c.cat for c in products | unique:'cat'">
    

    ...so as to select the cat field.

  • Then the | filter:query does not know by what property to filter; change it as | filter:{cat:query}

You will have to do something special, if no selection means no filter; currently it will match no products. See fiddle: http://jsfiddle.net/n7ZCg/

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

1 Comment

Thanks a lot, this is exactly what I needed. I was indeed suspecting that my ng-options were not set at the right level, but couldn't figure out how to fix it. Makes perfect sense now that you explained it! As for the "no products" issue, I just removed the 0 value to make it work.

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.