Aysha Azura Aysha Azura - 6 months ago 107
AngularJS Question

Binding dynamic values to ng-model of a check-box with in a ng-repeat

Using angular js i hvae an object like this

this.set = [{
"display": "Name",
"pass": "name"
}, {
"display": "Subject",
"pass": "subject"
}, {
"display": "Batch",
"pass": "batch"
}]


From another object I am displaying the details in my page. I want to search from the 2nd object.
I have provided check boxes name,batch and subject. The user can select the category for searching

<input type="text" ng-model="query.$">


This is the search input filed and the check-boxes are provided inside ng-repeat

<div flex class="filters" layout="row" ng-repeat="menu in menu">
<md-checkbox class="md-primary" ng-model="query.{{menu.pass}}">
{{menu.display}}
</md-checkbox>
</div>


with
{{menu.display}}
I am displaying the names correctly. Now i want to dynamically generate the ng-model also. How is this possible?

Answer

The ng-model attribute already expects an angular expression, so throwing in the curly braces inside that will not work, instead try something like:

<div flex class="filters" layout="row"  ng-repeat="menu in set">
    <md-checkbox  class="md-primary" ng-model="query[menu.pass]">
       {{menu.display}}
    </md-checkbox>
</div>

So now it's just setting query.batch by passing in the value of menu.pass.

DEMO: https://jsfiddle.net/qvw9bmhe/32/

Just click on the names and see the query object update.

Comments