Reputation: 1230
I want to change my ng-model name (in the html input tag) for each input tag dynamically. For example if my json file looks like:
[{cows: 0, pigs: 14, roosters: 2, horses: 23, goats: 21}]
and I am iterating through the properties of the json object ("items") using ng-repeat, what should I put in for ng-model="????" to bind that specific input with the specific object property (animal)?
<div ng-app="myApp" ng-controller="MainCtrl">
<form class="idea item">
<div ng-repeat="(key, value) in items[0]">
<label>{{key}}</label>
<input type="range" value="{{value}}" min="0" max="4" ng-model="????" />
</div>
<input type="submit" ng-click="save()" />
</form>
</div>
If I wrote it out statically without using ng-repeat, the inputs would look like:
<input type="range" value="{{value}}" min="0" max="4" ng-model="items[0].cows" />
<input type="range" value="{{value}}" min="0" max="4" ng-model="items[0].pigs" />
<input type="range" value="{{value}}" min="0" max="4" ng-model="items[0].roosters" />
<input type="range" value="{{value}}" min="0" max="4" ng-model="items[0].horses" />
<input type="range" value="{{value}}" min="0" max="4" ng-model="items[0].goats" />
However, I want this to be dynamic as I don't know what property names to expect.
Upvotes: 2
Views: 863
Reputation: 48147
Just use the associative indexing:
<input type="range" value="{{value}}" min="0" max="4" ng-model="items[0][key]" />
In other words, you can always access variables via the associative array. The following are equivalent:
item[0].pigs
item[0]['pigs']
You can use that to your advantage, since you know the key
in your repeater.
Upvotes: 3