如何获取ng-repeat生成的多个输入框的独立值?
解决AngularJS ng-repeat输入框值同步问题:获取每个输入框独立值
你遇到的问题核心原因很明确:所有生成的输入框都绑定到了catalog.description和catalog.quantity这两个单一变量上,不管有多少个输入框,它们指向的都是同一个内存地址,所以输入时自然会同步更新。要实现每个输入框的独立值,我们需要把catalog改成数组结构,让每组输入对应数组里的一个独立对象,再结合$index来绑定对应的数组元素。
第一步:修改控制器代码
把原来的单一catalog对象改成数组,并且在初始化时创建对应数量的对象(每个对象包含description和默认值为1的quantity):
$scope.catalog = []; // 从对象改为数组 $scope.catalogNumber = catalogNumber; $scope.initializeModal = initializeModal; $scope.quickAdd = quickAdd; function catalogNumber(num) { return new Array(num); } // 修改quickAdd函数,直接读取数组里的所有值 function quickAdd() { console.log($scope.catalog); // 现在会输出包含5个独立对象的数组 } function init() { $scope.number = 5; // 初始化catalog数组,生成5个带默认值的对象 $scope.catalog = Array.from({length: $scope.number}, () => ({ description: '', quantity: 1 })); }
第二步:修改HTML代码
调整ng-repeat的循环目标,直接遍历catalog数组,并且用catalog[$index].xxx来绑定每个输入框的model,确保每个输入对应数组里的独立元素:
<form class="quick-add-form" method="post"> <label class="quick-add-label">Enter the catalog number and quantity</label> <div class="quick-add"> <div class="catalog-list"> <label class="catalog-number-label" for="catalog-number-input">Catalog Number:</label> <!-- 直接遍历catalog数组,用$index绑定对应元素 --> <div ng-repeat="item in catalog track by $index"> <input id="catalog-number-input-{{$index}}" class="catalog-number-input" type="text" ng-model="catalog[$index].description" validate-input> </div> </div> <div class="qnty-list"> <label class="pdt-qnty-label" for="pdt-qnty-input">Quantity:</label> <!-- 保持和catalog-list的循环一致,确保索引对应 --> <div ng-repeat="item in catalog track by $index"> <input id="pdt-qnty-input-{{$index}}" class="pdt-qnty-input" type="number" pattern="[0-9]*" inputmode="numeric" min="1" max="999" ng-model="catalog[$index].quantity" name="qty-{{$index}}" maxlength="3"> </div> </div> </div> <div> <button type="submit" class="btn btn-danger cta-button quick-add-btn" ng-click="quickAdd()">Add to List</button> </div> </form>
关键改动说明
- 数据结构切换:从单一对象改为数组,让每个输入组对应数组的一个索引位置,确保数据独立。
- model绑定调整:用
catalog[$index].description和catalog[$index].quantity替代原来的单一变量,每个输入框绑定数组里的独立对象属性。 - 表单name属性优化:把
name="qty"改成name="qty-{{$index}}",避免多个表单元素name重复,符合HTML表单规范。
现在你再测试输入,每个输入框的值都会独立保存,点击“Add to List”按钮后,quickAdd函数会输出包含所有独立值的数组,完美解决同步问题。
内容的提问来源于stack exchange,提问作者Arfat
相关产品推荐
相关产品推荐

