表单提交不会更新绑定到radiobutton的模型

时间:2014-12-06 21:55:06

标签: javascript angularjs

这是我的HTML:

<form role="form" ng-submit="submit()">
    <div class="form-group">
        <div class="radio" ng-repeat="answer in answers">
            <label>
                <input type="radio" name="answer" ng-model="submittedAnswer" value="{{$index}}" /> {{ answer }}
              </label>
         </div>
     </div>
     <div class="form-group">
         <button type="submit" class="btn btn-primary">Далее</button>
      </div>
</form>

在角度控制器中我有这段代码:

$scope.submittedAnswer = 0;

$scope.submit = function () {
    answers.push($scope.submittedAnswer);

    console.log($scope.submittedAnswer);
}

提交时我总是0。似乎只有关于radiobutton的问题。我试图将模型绑定到简单的文本输入,并且一切正常。有什么建议?顺便说一句,有没有办法避免模型的初始化(我不希望最初检查任何radiobutton)?

2 个答案:

答案 0 :(得分:0)

您必须在ng-repeat模型中使用$ parent来绑定模型。

var myapp = angular.module('myApp',[]);

myapp.controller('myController', function($scope){

  $scope.answers = ['One','Two','Three'];
  
  $scope.submit = function(){
    console.log($scope.submittedAnswer);
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="myController">
<form role="form" ng-submit="submit()" ng-init="submittedAnswer = 0">
                <div class="form-group">
                    <div class="radio" ng-repeat="answer in answers">
                        <label>
                            <input type="radio" name="answer" ng-model="$parent.submittedAnswer" value="{{$index}}" /> {{ answer }}
                        </label>
                    </div>
                </div>
                <div class="form-group">
                    <button type="submit" class="btn btn-primary">Далее</button>
                </div>
            </form>
    </div>
  </div>

答案 1 :(得分:0)