Angularjs ng-model 的动态名称
Angularjs dynamic name of ng-model
我正在使用 AngularJS 并且我使用了 ng-repeat
块。我想使用 unique/dynamic ng-model
名称。这段代码的想法是,当我单击按钮时,我会增加文本框的值。参数名称在调试器中是正确的,但值没有改变。下面是我使用的代码,但它不起作用,我找不到原因。谁能帮帮我?
<tr ng-repeat="item in resultShoppingCart track by $index">
<td class="price" ng-bind="item.unitPrice"><span></span></td>
<td class="qty">
<input class="form-control input-sm" type="text" ng-value="item.quantity" ng-model="Qty['{{$index}}']">
<a href=""><i class="fa fa-plus" ng-click="addQuantity(item.quantity, item.productId, $index)"></i></a> <a href="#"><i class="fa fa-minus"></i></a>
</td>
<td class="price" ng-bind="item.price"><span>.00</span></td>
<td class="action"><a ng-click="delete(userId,item.productId)">Delete item</a></td>
</tr>
还有我的控制器。
$scope.addQuantity = function (currentQuantity, productId, i) {
$scope["Qty['" + i + "']"] = currentQuantity + 1;
alert($scope["Qty['" + i + "']"]);
}
因为 '{{$index}}'
表达式的结果将是 '{{$index}}'
本身。因此,您必须将表达式更改为 Qty[$index]
,而不是在 ng-model
中使用 Qty['{{$index}}']
,这样插值才能正确计算它。
但我建议使用 item.quantity
,它最终将是独一无二的。无需维护单独的对象(因此我看不出有任何理由单独保存数量)。
<td class="qty">
<input class="form-control input-sm" type="text" ng-value="item.quantity" ng-model="item.quantity" >
<a href=""><i class="fa fa-plus" ng-click="addQuantity(item)"></i></a> <a href="#"><i class="fa fa-minus"></i></a>
</td>
代码
$scope.addQuantity = function (item) {
item.quantity = item.quantity + 1;
}
我正在使用 AngularJS 并且我使用了 ng-repeat
块。我想使用 unique/dynamic ng-model
名称。这段代码的想法是,当我单击按钮时,我会增加文本框的值。参数名称在调试器中是正确的,但值没有改变。下面是我使用的代码,但它不起作用,我找不到原因。谁能帮帮我?
<tr ng-repeat="item in resultShoppingCart track by $index">
<td class="price" ng-bind="item.unitPrice"><span></span></td>
<td class="qty">
<input class="form-control input-sm" type="text" ng-value="item.quantity" ng-model="Qty['{{$index}}']">
<a href=""><i class="fa fa-plus" ng-click="addQuantity(item.quantity, item.productId, $index)"></i></a> <a href="#"><i class="fa fa-minus"></i></a>
</td>
<td class="price" ng-bind="item.price"><span>.00</span></td>
<td class="action"><a ng-click="delete(userId,item.productId)">Delete item</a></td>
</tr>
还有我的控制器。
$scope.addQuantity = function (currentQuantity, productId, i) {
$scope["Qty['" + i + "']"] = currentQuantity + 1;
alert($scope["Qty['" + i + "']"]);
}
因为 '{{$index}}'
表达式的结果将是 '{{$index}}'
本身。因此,您必须将表达式更改为 Qty[$index]
,而不是在 ng-model
中使用 Qty['{{$index}}']
,这样插值才能正确计算它。
但我建议使用 item.quantity
,它最终将是独一无二的。无需维护单独的对象(因此我看不出有任何理由单独保存数量)。
<td class="qty">
<input class="form-control input-sm" type="text" ng-value="item.quantity" ng-model="item.quantity" >
<a href=""><i class="fa fa-plus" ng-click="addQuantity(item)"></i></a> <a href="#"><i class="fa fa-minus"></i></a>
</td>
代码
$scope.addQuantity = function (item) {
item.quantity = item.quantity + 1;
}