2

I am iterating over list of objects using key value pair ng-repeat .I want to add a dynamic ng-model to a checkbox. I have searched a lot but i didn't find any solution.I though found a similar question - define dynamic ng-model inside key value pair ng-repeat but it seems to be unanswered.

<div id="details_{{key}}" ng-repeat="(key,value) in value" >
<input type="checkbox" ng-model="" ng-change="single_chk()">
</div>

How can i add dynamic property for ng-model for the above ng-repeat and i have to pass that value inside ng-change too?

Community
  • 1
  • 1
Namdeo Karande
  • 403
  • 1
  • 3
  • 19
  • Possible duplicate of [Dynamically assign ng-model](http://stackoverflow.com/questions/14183614/dynamically-assign-ng-model) – Asav Vora May 10 '17 at 07:27

1 Answers1

1

You can use the the key or $index to create the model 'on the fly' but have it as object notation so it's easily accessible in the controller. Your ng-repeat should have a name other than 'value' btw as it might cause issues with the (key, value), like the following. I'd also recommend getting used to using vm:

<div id="details_{{key}}" ng-repeat="(key, value) in vm.objArray">
  <input type="checkbox" ng-model="vm.model.{{key}}" ng-change="vm.single_chk(key)">
</div>

Then in your controller, accessing this.model will give you an object with all the models underneath it, regardless of what the key is. Your ng-change, passed in the key that you're using on the model itself, so easily accessible:

single_chk(key) {
  // this.model[key] holds the model for the key passed in
}
rrd
  • 5,789
  • 3
  • 28
  • 36