使用数组ng-model

Using an array of ng-model

本文关键字:ng-model 数组      更新时间:2023-09-26

我是AngularJS新手。在我的场景中,用户必须创建一个mcq问题。这个问题有4个默认选项,其中一个选项是正确的。现在作为老师的用户可以为问题提供多于或少于4个选项。所以选项的数量是可变的。如果硬编码输入如下

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

等等,效果很好。我想在这里使用动态解,所以老师提供多少选项并不重要。

我想做的是

  1. 美元范围。McQ_options = $scope.input_0,$scope。input_1…]
  2. 在html模板中使用ng-repeat并做如下操作

    <div ng-repeat = "input in mcq_options">
    <input name = "input1" type = "text", class = "form-control" ng-model = "input" required>
    
  3. 用于从数组中删除拼接项

  4. 用于在数组
  5. 中添加更多push条目

解决方案非常简单(Associated PLUNKER):

1创建一个空数组,你可以存储所有的选项,在你的控制器

var inputArray = $scope.inputArray = [];

[2]创建一个函数来添加新的选项

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

[3]创建另一个函数来拼接一个选项项,该选项项接受要删除的选项的索引。

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

[4]你的视图可以是这样的:

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

注意:

  • ng-repeat指令中的track by $index有助于避免重复值错误。
  • ng-form指令帮助您验证每个在ng-repeat迭代中创建的模型。
  • 不要在ng-repeat指令中使用input值,而是使用ng-repeat的$index属性来直接引用它。如果不这样做,inputArray中的更改可能会影响当前输入的ngModel引用。例如,添加或删除选项会给你奇怪的行为。