Jackie
Jackie

Reputation: 23607

Angular and radio input not working with ng-model

So I have an Angular project with the following in my directive template

<div ng-repeat="poll in polls">
  <div ng-repeat="choice in poll.choices">
    <input type="radio" name="choice" ng-model="userVote" ng-value="choice.text">
                                {{choice.text}}
    <button ng-click="vote(userVote)">Vote!</button>
  </div>
</div>

And my controller has the following...

 $scope.vote = function(userVote){
  alert(userVote);
 }

But the alert says undefined, despite the {{choice.text}} showing up properly. There are no JS errors and the other functions in the controller work as expected.

Upvotes: 0

Views: 118

Answers (2)

Jesus is Lord
Jesus is Lord

Reputation: 15409

The only thing I know to do when you need to "set" inside an ng-repeat (or any directive that creates a new scope) is to, in your controller at the top, do something like:

$scope.model = {};

And then every ng-model that is inside a new scope should have model. in front of it. This will make it so you don't have to use $parent. This has the advantage of, should you add something like ng-if somewhere you don't have to do things like $parent.$parent.

I suppose if you're using a newer version of angular there's also getters and setters you can use with ng-model-options.

Upvotes: 1

Jackie
Jackie

Reputation: 23607

Problem was related to ng-repeat creating its own scope. This does work as expected...

<input type="radio" name="choice" ng-model="$parent.userVote" ng-value="choice.text">

However, I have also read that the $parent scope is bad practice so I am still researching and the check is still open.

(hope this works)

Simple Example Failing

Simple Example Passing

Upvotes: 1

Related Questions