0

I have a form:

<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>

with some 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>

and an Angular controller:

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

I want to dynamically add answer options to a question by pressing the button. The problem is that when I submit the form, the answers are not present in $scope.exercise. I suspect this is because these fields are added after the original html is rendered.

How can I fix this?

1 Answer 1

2

This isn't really the Angular way of doing things. You want to modify a data structure that is binded to the view. Create an array of answers, and simply push to that array when you want another row to show up:

<div id="options">
    <p ng-repeat="answer in answers">
        <input type="text" ng-model="answer.text" />
    </p>
</div>

<button type="button" ng-click="newAnswer()">Add answer</button>

And the new controller logic:

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

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

    $scope.submitExercise = function() {
        console.log($scope.answers);
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.