将 ng-model 数组绑定到固定数量的文本框
Binding ng-model array to fixed number of textboxes
如何将数组形式的 ng-model 绑定到固定数量的文本框?
假设我有三个文本框,它们都是可选的,如何将 ng-model 绑定到这些文本框?
<input type="text" name="optionalField[]">
<input type="text" name="optionalField[]">
<input type="text" name="optionalField[]">
您可以在任何文本框中输入内容(例如,仅限文本框 2 和 3),当您保存它时,它将变成 optionalField: ['text2', 'text3']
。
放置文本的位置无关紧要;重要的是文本框的顺序。因此,当您再次显示视图时,它只会绑定到第一个和第二个文本框。如果您只在文本框 3 上输入,它将被绑定到文本框 1,依此类推。
更新:
刚刚使用 的答案并将其修改为 return 过滤值数组。
http://codepen.io/anon/pen/ozpxGq?editors=1011
像这样:
<input type="text" name="optionalField[]" ng-model="optionalField[0]">
<input type="text" name="optionalField[]" ng-model="optionalField[1]">
<input type="text" name="optionalField[]" ng-model="optionalField[2]">
在ng-repeat
中你可以使用$index
<input type="text" name="optionalField[]" ng-model="optionalField[$index]">
如何将数组形式的 ng-model 绑定到固定数量的文本框?
假设我有三个文本框,它们都是可选的,如何将 ng-model 绑定到这些文本框?
<input type="text" name="optionalField[]">
<input type="text" name="optionalField[]">
<input type="text" name="optionalField[]">
您可以在任何文本框中输入内容(例如,仅限文本框 2 和 3),当您保存它时,它将变成 optionalField: ['text2', 'text3']
。
放置文本的位置无关紧要;重要的是文本框的顺序。因此,当您再次显示视图时,它只会绑定到第一个和第二个文本框。如果您只在文本框 3 上输入,它将被绑定到文本框 1,依此类推。
更新:
刚刚使用
像这样:
<input type="text" name="optionalField[]" ng-model="optionalField[0]">
<input type="text" name="optionalField[]" ng-model="optionalField[1]">
<input type="text" name="optionalField[]" ng-model="optionalField[2]">
在ng-repeat
中你可以使用$index
<input type="text" name="optionalField[]" ng-model="optionalField[$index]">