J145
J145

Reputation: 699

ng-repeat scope and dynamic ng-model

Quick questions. Im generating part of a form dynamically, namely the radio buttons part and I am using an ng-repeat. To do this I have the following code to loop through and list the radio button options:

 <div ng-repeat="choice in question.choices">
     <input name="{{q.name}}" type="radio" value={{choice.id}} ng-model="choice_[q.answer]" required /> {{choice.choice}}
 </div> 

I have two issues with this, firstly, im not sure if I am correctly assigning my ng-model dynamically.

Secondly once the model is created it seems to be in its own scope and unusable outside of the repeat due to it being encapsulated within the repeat div.

Is there a way I would be able to access this model? perhaps just passing it through the parent scope using $parent or so?

Any help would be appreciated.

Thanks

Upvotes: 1

Views: 562

Answers (1)

Lord Herky
Lord Herky

Reputation: 21

I created a plunker to show how to access your model:

Model access demo

<input type="radio" value={{choice.id}} ng-model="$parent.choice" required /> {{choice.choice}}

I used the same model name for every input in the repeat. This way whichever input is selected becomes the active model. That should solve your model naming issue.

Secondly, ng-repeat creates a scope for every template it produces, so you do want to use $parent to access the model on your controllers scope.

Upvotes: 0

Related Questions