deekay
deekay

Reputation: 607

Angular - Filtering with checkboxes

I am new to Angular and i just cant wrap my head around that problem.

I have several checkboxes which will have a unique value each, like so:

<label ng-repeat="c in classes">
    <input type="checkbox"  ng-model="query" ng-true-value='{{c.name}}'>
    <span>{{c.name}}</span>
</label>

Next i have this set of divs that should be filtered on a specific value like card.name , like so:

<div ng-repeat="card in cards | filter:query">
  <h2>{{card.name}}</h2>
  <p><em>{{card.text}}</em></p>
</div>

When checkbox with value 'Peter' is checked, all cards with card.name=Peter are shown. When checkbox 'Peter' and 'John' are shown all cards with card.name=Peter and =John are shown. How can i realize this?

I guess its more of a general concept/markup question...

Upvotes: 0

Views: 881

Answers (1)

TheSharpieOne
TheSharpieOne

Reputation: 25736

You don't need to have two different variables, in fact that is the problem. Angular doesn't know how to tie them together.

The filter can look deep into the object for a specific key set to a specific value. In my example the filter looks for this particular selected attribute, only showing ones that are set to true Keeping everything in the same object keeps everything tied together.

<label ng-repeat="c in classes">
    <input type="checkbox"  ng-model="c.selected" />
    <span>{{c.name}}</span>
</label>

<div ng-repeat="card in classes | filter:{selected:true}">
    <h2>{{card.name}}</h2>
    <p><em>{{card.text}}</em></p>
</div>

Here is the data:

$scope.classes = [{
    name: "John",
    text: "Something about John"
},{
    name: "Peter",
    text: "Something about Peter"
}];

Note: that a selected attribute is added to each object when it is selected. This is the key we are filtering on.

Working example: http://jsfiddle.net/TheSharpieOne/y2UW7/

UPDATE:

After re-reading the question, it appeared to me that there would be multiple cards for the same name. A different approach would be needed.

In this case, multiple variables are needed, a list of checkboxes and a list of "cards". We also need a var to track which boxes are selected.

In this case we use a function to filter the list as 1 checkbox could change many "cards"

Example: http://jsfiddle.net/TheSharpieOne/y2UW7/1/

Upvotes: 1

Related Questions