为输入创建动态 ng-model
Create a dynamic ng-model for an input
如何使输入的 ng-model
动态化?
静态 ng 模型:
<input type="text" ng-model="myModel.firstName" />
动态 ng 模型:
$scope.myInputs = [{ key: "firstName"}, { key: "lastName" }];
<div ng-repeat="input in myInputs">
<input type="text" ng-model="myModel[input.key]" />
</div>
myModel[input.key]
似乎计算不正确。
在myInputs[input.key]
中,input.key
不是索引。因此您无法访问期望值。
您可以
<div ng-repeat="input in myInputs">
<input type="text" ng-model="input.key" />
</div>
或者
<div ng-repeat="input in myInputs track by $index">
<input type="text" ng-model="myInputs[$index].key" />
</div>
如何使输入的 ng-model
动态化?
静态 ng 模型:
<input type="text" ng-model="myModel.firstName" />
动态 ng 模型:
$scope.myInputs = [{ key: "firstName"}, { key: "lastName" }];
<div ng-repeat="input in myInputs">
<input type="text" ng-model="myModel[input.key]" />
</div>
myModel[input.key]
似乎计算不正确。
在myInputs[input.key]
中,input.key
不是索引。因此您无法访问期望值。
您可以
<div ng-repeat="input in myInputs">
<input type="text" ng-model="input.key" />
</div>
或者
<div ng-repeat="input in myInputs track by $index">
<input type="text" ng-model="myInputs[$index].key" />
</div>