简体   繁体   English

如何更改 <select>从控制器使用angularJS的值?

[英]How to change a <select> value from controller using angularJS?

I am having a select element with 1-10 options as: 我有一个带有1-10个选项的select元素,例如:

<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>

while on controller side looks like: 而在控制器端看起来像:

$scope.quantityValues = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

prerequisite: initially product.quantity < product.selected_size.qty_avail 先决条件:最初product.quantity <product.selected_size.qty_avail

what i want to do that when I try to select other option such that if value corresponding this new option is greater than the available quantity than update and display last selected option ie one where selected option value was less than available quantity: 当我尝试选择其他选项时要执行的操作,以便如果此新选项对应的值大于可用数量,而不是更新并显示上一个所选选项,即所选选项值小于可用数量的选项:

$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

    }
}

example: if available_quantity=4; 例如:if available_quantity = 4; previous selected product quantity=2; 先前选择的产品数量= 2; current selected product quantity=8 当前选择的产品数量= 8

current o/pi am getting: still 8 is displayed in select html tag 当前的o / pi正在获取:在html标记中仍显示8

expected: display previous selected product quantity ie display 2 预期:显示先前选择的产品数量,即显示2

Remember the old value in your controller (I placed it into the product variable). 记住控制器中的旧值(我将其放入产品变量中)。

HTML: 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;
    }
};

Example in Plnkr Plnkr中的示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM