带有动态添加数据绑定的Angular表单提交

时间:2016-03-28 15:42:36

标签: javascript angularjs

我有一张表格:

<form ng-controller="NtCtrl" ng-submit="submitExercise()">

  <!-- Question input -->
  <input ng-model="exercise.question"/>

  <!-- Dynamically add answer options here -->
  <div id="options"></div>

  <!-- Click this button to add new field -->
  <button type="button" onclick="newAnswer()">Add answer</button>

  <!-- Click this button to submit form -->
  <button type="submit">Submit question</button>
</form>

使用一些JavaScript:

<script type="text/javascript">

  var count = 1;

  function newAnswer() {
    var input = document.createElement('input');
    var attr = document.createAttribute('ng-model');
    attr.value = "exercise.answers." + qid; 
    input.setAttributeNode(attr);

    document.getElementById('options').appendChild(input);

    count ++;
  }

</script>

和Angular控制器:

angular.module('myApp').controller('NtCtrl', function($scope) {
    $scope.exercise = {};
    $scope.submitExercise = function() {
        console.log($scope.exercise);
    });
});

我想通过按下按钮动态地为问题添加答案选项。问题是,当我提交表单时,$scope.exercise中没有答案。我怀疑这是因为这些字段是在渲染原始html之后添加的。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

这并不是Angular的做事方式。您想要修改绑定到视图的数据结构。创建一个答案数组,当您想要显示另一行时,只需推送到该数组:

angular.module('myApp').controller('NtCtrl', function($scope) {
    $scope.answers = [];

    $scope.newAnswer = function() {
        $scope.answers.push({text:"Sample"});
    }

    $scope.submitExercise = function() {
        console.log($scope.answers);
    });
});

新的控制器逻辑:

{{1}}