0

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.

3
  • There is no problem with your code. Can you try to reproduce it in a fiddle? Commented Aug 2, 2014 at 16:08
  • Could be cause I was using a partial from a directive? If so I may need to add that info as well. Commented Aug 2, 2014 at 16:37
  • Nope had nothing to do with directives just a Angular Gotcha! Commented Aug 2, 2014 at 16:49

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Your links weren't working when I clicked them, but I think maybe the site is having issues since I couldn't create a new Angular plunk.
1

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.

1 Comment

Great idea! I will add this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.