How to give value dynamically for ng-model in angularjs?

angularjs

Solution

Since ng-repeat creates a child scope for each type/item/iteration, we need to associate the ng-model for each type with the parent scope, rather than the child scope. One way to do that is to use $parent:

<input type="checkbox" ng-model="$parent[type]">{{ type }}

If $scope.types is defined like in @Alex's answer, then properties `typeOne`, `typeTwo`, and `typeThree` will appear on the parent scope if the corresponding checkbox is clicked, and the value of the property will be `true`. If a checked checkbox is clicked again, the property remains, and the value will switch to `false`. Your code would therefore have to check for non-existent properties and for properties that exist with the value set to true or false. That's a little messy.

I would prefer to predefine an array of objects on the parent scope, where each object has the type (name), and a boolean to indicate if it is selected or not:

$scope.types = [ 
  {name: 'typeOne', selected: false},
  {name: 'typeTwo', selected: false},
  {name: 'typeThree', selected: false}];

Then, $parent is not required (because the value of "type" will be a reference to the parent object, rather than a copy of the parent property's (primitive) value):

<input type="checkbox" ng-model="type.selected">{{ type.name }}

See also What are the nuances of scope prototypal / prototypical inheritance in AngularJS? to learn more about ng-repeat and child scopes.

Problem

Here I am generating an html element dynamically using `ng-repeat` eg ``` <div ng-repeat="type in types"> <input type="checkbox" ng-model="{{type}}" />{{ type }} </div> ``` I want to set the type value for ng-model. Is it possible or else I want to set that type value for ng-true-value like this ``` <div ng-repeat="type in types"> <input type="checkbox" ng-model="{{type}}" ng-true-value="{{type}}" />{{ type }} </div> ```

Original source

Related problems