我有一个包含 1-10 个选项的选择元素:
<select id="selVal" ng-model="product.quantity" ng-options="o as o for o in quantityValues" ng-change="updateDelta(product.quantity, {{product.quantity}}, product.selected_size.qty_avail)"></select>
在 Controller 端看起来像:
$scope.quantityValues = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
先决条件:最初是 product.quantity < product.selected_size.qty_avail
当我尝试选择其他选项时,我想做的是,如果对应于此新选项的值大于可用数量,则更新并显示最后选择的选项,即所选选项值小于可用数量的选项:
$scope.updateDelta = function(currentSelectedVal, prevSelectedVal, selectedProductAvailQty) {
if(product.quantity > selectedProductAvailQty) {
//than
#scope.product.quantity = prevSelectedVal;//still in product.quantity in view previous value is not displayed
}
}
示例:如果 available_quantity=4;先前选择的产品数量=2;当前选择的产品数量=8
我得到的当前 o/p:仍然 8 显示在选择的 html 标记中
预期:显示之前选择的产品数量即显示2
最佳答案
记住 Controller 中的旧值(我将其放入产品变量中)。
HTML:
<select ng-model="ctrl.product.quantity" ng-change="ctrl.updateDelta(ctrl.product.quantity)" ng-options="o as o for o in ctrl.quantityValues"></select>
Controller :
vm.product = {
quantity: 4,
qty_avail: 6,
prevSelected: this.quantity
};
vm.updateDelta = function(newVal) {
if (newVal > vm.product.qty_avail) {
vm.product.quantity = vm.product.prevSelected;
}
else
{
vm.product.prevSelected = newVal;
}
};
关于javascript - 如何使用 angularJS 从 Controller 更改 <select> 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37296080/