数据绑定多个输入的 angularjs 方法是什么? [英] What is the angularjs way to databind many inputs?
问题描述
我正在学习 angularjs,我希望能够让用户输入许多输入.当输入这些输入时,list
数组元素应该相应地改变.我想尝试使用 ngRepeat 指令,但我读到它,因为它创建了一个我无法数据绑定的新范围:
<label>输入{{$index+1}}:</label><input ng-model="item" type="text"/>
我想知道我是否应该使用自定义指令来执行此操作或以不同方式进行处理.
如果您的 list
是一个对象数组(而不是原始数组),那么您的运气会更好.即使使用 ng-repeat
创建了新范围,这也能正常工作:
<label>输入{{$index+1}}:</label><input ng-model="item.value" type="text"/>
带有以下控制器:
function TestController($scope) {$scope.list = [ { value: 'value 1' }, { value: 'value 2' }, { value: 'value 3' } ];}
以这个小提琴为例.
另一方面,如果您尝试绑定到一个字符串数组,新的作用域会导致问题,因为您正在修改的值不会绑定到原始数组字符串原语(如 这个小提琴 示例).
I'm learning angularjs and I want to be able let the user enter many inputs. When these inputs are entered the list
array elements should change accordingly. I wanted to try using ngRepeat directive but I read that since it creates a new scope I cannot databind:
<div ng-repeat="item in list">
<label>Input {{$index+1}}:</label>
<input ng-model="item" type="text"/>
</div>
I was wondering if I should be using a custom directive to do this or approach it differently.
You'll have better luck if your list
is an array of objects (as opposed to an array of primitives). This works fine even though a new scope is created with ng-repeat
:
<div ng-repeat="item in list">
<label>Input {{$index+1}}:</label>
<input ng-model="item.value" type="text"/>
</div>
with a controller of:
function TestController($scope) {
$scope.list = [ { value: 'value 1' }, { value: 'value 2' }, { value: 'value 3' } ];
}
See this fiddle as an example.
On the other hand if you are trying to bind to an array of strings the new scope will cause a problem as the values you are modifying will not be tied to the original array string primitives (as in this fiddle example).
这篇关于数据绑定多个输入的 angularjs 方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!