使用数组ng-model
Using an array of ng-model
我是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>
等等,效果很好。我想在这里使用动态解,所以老师提供多少选项并不重要。
我想做的是
- 美元范围。McQ_options = $scope.input_0,$scope。input_1…]
在html模板中使用ng-repeat并做如下操作
<div ng-repeat = "input in mcq_options"> <input name = "input1" type = "text", class = "form-control" ng-model = "input" required>
用于从数组中删除拼接项
- 用于在数组 中添加更多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
引用。例如,添加或删除选项会给你奇怪的行为。
相关文章:
- ng将数组重复解析为字符串
- ng-repeat不绑定ng-model对象数组
- 替换 ng-repeat 数组会导致奇怪的重新渲染
- 使用 ng-model 将数组中的选择列表发布到服务器
- 如何在 meanJS 中存储 ng-repeat 数组表单数据
- ng在数组中重复数组
- BackboneJS如何删除Model数组的项
- Angularjs ng使用数组中相同的元素重复动画
- Angularjs -从输入文本ng-model填充json数组
- 连接到ng-model的Angular数组值
- 在select中将ng-model绑定到数组大小
- Angularjs - ' ng-model '在多维数组中
- * ng用于数组的动态字符串插值
- AngularJS -访问一个带有ng-model动态名称的输入数组
- 滚动到ng-repeat数组中最后添加的记录
- 绑定ng-options数组中的一个属性
- 不能从AngularJS数据中NG-Repeat数组(英雄联盟)
- 动态添加项目到ng-repeat数组javascript
- AngularJS的ng-repeat数组的数组
- 如何让AngularJS更新DOM上的ng-repeat数组拼接?$scope.$apply()返回一个错误