Search code examples
angularjsangularjs-ng-repeatangular-ngmodelangularjs-ng-model

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


Inside my controller I have an array of objects like this:

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

I have provided checkboxes: name, batch and subject. Checking the checkboxes will filter a category.

HTML:

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

{{menu.display}} Is displaying the names correctly. Now i want to dynamically bind the ng-model also. How is this possible?


Solution

  • 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.