首页 > 解决方案 > 在 ng-repeat 内以编程方式更新 ng-model 时触发 ng-change

问题描述

我阅读了与此相关的主题并找到了以下内容,但我仍然被卡住了。

如何 $watch 由 ng-repeat 创建的模型的变化?

我正在尝试使用以下代码实现加减计数器。现在,每当通过单击 +/- 按钮更新 ng-model 时,我都想触发 ng-change。我知道当 ng-model 以编程方式更新时,ng-change 不会触发。但是引用的 Stackoverflow 有解决方案,可以在 ng-model 上添加 $watch。但是如果我创建单独的控制器,它就可以工作,而不是在当前控制器内工作。ng-change 正在调用当前控制器内部的函数。怎么解决??

<div class="input-group" ng-repeat="product in oc.itemdetail.lines">
    <input type="button" value="-" class="minus"
           ng-click="product.line.total = product.line.total - product.stepCount">

    <input  type="number"  ng-if="condition 1" ng-model="product.line.total" min="" max="" 
            step="product.stepCount" oninput="some condition"
            ng-change="oc.function1()" />
    <input  type="number"  ng-if="condition 2" ng-model="product.line.total" min="" max=""
            step="product.stepCount" oninput="some condition"
            ng-change="oc.function2()" />

    <input type="button" value="+" class="plus"
           ng-click="product.line.total = product.line.total + product.stepCount">

</div>

我上面有两个输入框,根据 ng-if 条件,一次显示一个。每个 ng-change 都在当前控制器中调用不同的函数。如果我放置单独的控制器,然后单击 +/- 按钮,以下功能就会触发。但我想在 ng-change 中调用函数

$scope.$watch('Count', function (oldValue, newValue) {
    if (newValue != oldValue)
      console.log(oldValue, newValue);
});

标签: javascriptangularjsangularjs-ng-repeatangularjs-ng-modelangularjs-ng-change

解决方案


代码应避免将onchange属性与ng-model指令一起使用。该ng-if指令使用了大量资源。如果使用它的唯一原因是切换ng-change功能,则应避免使用它。ng-change可以在控制器中选择功能。

<div class="input-group" ng-repeat="product in oc.itemdetail.lines">
    <input type="button" value="-" class="minus"
           ng-click="oc.decrement(product)">

    <input  type="number"  ng-model="product.line.total" min="" max="" 
            step="product.stepCount" ng-change="oc.update(product)" />

    <input type="button" value="+" class="plus"
           ng-click="oc.increment(product)">

</div>

避免模​​板中的复杂公式。而是将它们放在控制器中:

oc.update = function(product) {
   if (oc.<condition 1>) {
     oc.function1();
   };
   if (oc.<condition 2>) {
     oc.function2();
   };
};

出于性能原因,请避免使用观察者。而是使用更改模型的函数来调用更新操作:

oc.decrement = function(product) {
    product.line.total = product.line.total - product.stepCount;
    oc.update(product);
};

oc.increment = function(product) {
    product.line.total = product.line.total + product.stepCount;
    oc.update(product);
};

将复杂的表达式放入控制器使代码更易于理解、调试、测试和维护。


推荐阅读