我无法理解的简单 AngularJS 问题。
Plunkr:http://plnkr.co/edit/OjaooVOQBEETkhaZFbWG?p=preview
HTML;
<div ng-repeat="label in likedLabels">
<input ng-model="likedLabels[$index]">
</div>
{{likedLabels}}
<button ng-click="addInput()">+add more inputs</button>
JS:
$scope.likedLabels = ['']
$scope.addInput = function(){
$scope.likedLabels.push('');
}
我基本上试图创建一种用户操作的方式来添加输入框并将其中的内容链接到模型。我在这里做错了什么?
最佳答案
在数组中使用对象而不是基元。像 ng-repeat
这样的指令为数组中的每个重复项创建单独的子作用域。
由于原型(prototype)继承,对象将作为原始对象的引用传递到子范围,而基元(字符串、 bool 值等)则不会。因此范围树中没有基元的数据绑定(bind)
HTML
<div ng-repeat="item in likedLabels">
<input ng-model="item.label">
</div>
JS
$scope.likedLabels = []
$scope.addInput = function() {
$scope.likedLabels.push({label: ''});
}
关于javascript - AngularJS 添加表示数组模型的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20295067/