gpt4 book ai didi

javascript - 当 ng-model 在 ng-repeat 中以编程方式更新时触发 ng-change

转载 作者:行者123 更新时间:2023-11-30 19:12:45 26 4
gpt4 key购买 nike

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

How to $watch changes on models created by ng-repeat?

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

<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 都在当前 Controller 中调用不同的函数。如果我放置单独的 Controller ,则单击 +/- 按钮将触发以下功能。但是我想在 ng-change 中调用函数

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

最佳答案

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

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

避免在模板中使用复杂的公式。而是将它们放在 Controller 中:

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);
};

在 Controller 中放入复杂的表达式可以使代码更易于理解、调试、测试和维护。

关于javascript - 当 ng-model 在 ng-repeat 中以编程方式更新时触发 ng-change,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58308370/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com