akniazi
akniazi

Reputation: 732

Using an array of ng-model

I am new to AngularJS. In my scenario, the user has to create a mcq question. The question has 4 default option and one of the options is correct. Now the user who is teacher can give greater or less then 4 options for the question. So its a variable number of options. If hard code the input as follow

<input name = "input0" type = "text", class = "form-control" ng-model = "input_0" required>

<input name = "input1" type = "text", class = "form-control" ng-model = "input_1" required>

and so on it works good. I want to use dynamic solution here, so it does not matter how many options the teacher provide.

What I was trying to do is

  1. $scope.mcq_options = [$scope.input_0,$scope.input_1 ...]
  2. use ng-repeat in html template and do something like

    <div ng-repeat = "input in mcq_options">
    <input name = "input1" type = "text", class = "form-control" ng-model = "input" required>
    
  3. For removing splice entry from array

  4. For adding more push entry in array

Upvotes: 0

Views: 131

Answers (1)

ryeballar
ryeballar

Reputation: 30098

The solution is quite straightforward (Associated PLUNKER):

1 Create an empty array that you may store all your options, in your controller.

var inputArray = $scope.inputArray = [];

[2] Create a function to add new options.

$scope.addNewOption = function() {
   inputArray.push('');
};

[3] Create another function to splice an option entry that accepts the index of an option to remove.

$scope.removeOption = function(index) {
  inputArray.splice(index, 1);
};

[4] Your view can be something like this:

    <form name="form" novalidate>
      <div ng-repeat="input in inputArray track by $index" ng-form="subform">
        <input name="input" type="text" ng-model="inputArray[$index]" required> <button ng-click="removeOption($index)">Remove</button>
        <br>
        <span ng-show="subform.input.$error.required">This field is rqeuired</span>
      </div>
      <button ng-click="addNewOption()">Add New Option</button>
    </form>

Note:

  • The track by $index in the ng-repeat directive helps in avoiding duplicate values error.
  • The ng-form directive helps you in validating each models that is created in every ng-repeat iteration.
  • Instead of using the input value in the ng-repeat directive, use its direct reference by using the ng-repeat's $index property. If you dont't do this, changes in the inputArray may affect the current ngModel reference of your inputs. e.g. adding or removing options will give you weird behaviours.

Upvotes: 1

Related Questions