角度和无线电输入不适用于ng-model

时间:2014-08-02 15:50:19

标签: angularjs

所以我在我的指令模板

中有一个Angular项目
<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>

我的控制器有以下内容......

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

但警告说未定义,尽管{{choice.text}}正确显示。没有JS错误,控制器中的其他功能按预期工作。

2 个答案:

答案 0 :(得分:1)

问题与ng-repeat创建自己的范围有关。这确实按预期工作......

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

但是,我还读到$ parent范围是不好的做法所以我还在研究,检查仍然是开放的。

(希望这有效)

Simple Example Failing

Simple Example Passing

答案 1 :(得分:1)

当你需要&#34;设置&#34;时,我知道要做的唯一事情。在ng-repeat(或任何创建新范围的指令)中,在顶部的控制器中执行以下操作:

$scope.model = {};

然后新范围内的每个ng-model都应该在其前面model.。这将使您不必使用$parent。这样做的好处是,如果您在某个地方添加ng-if之类的内容,则不必执行$parent.$parent之类的操作。

我想如果您使用更新版本的棱角分支,那么您可以使用ng-model-options来获取吸气剂和镶嵌剂。

相关问题