javascript - 在 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);
});
解决方案
代码应避免将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);
};
将复杂的表达式放入控制器使代码更易于理解、调试、测试和维护。
推荐阅读
- c - 在 C 中使用 fgets 和 strtok 读取文件并将信息保存在喜欢的列表中
- angular - 如何在 Snackbar 中设置消息
- python - 熊猫,转换具有相同日期时间索引值的行
- oracle - Oracle SQL 表在 Create 语句上显示缺少右括号为什么?
- python - 使用 matplotlib python 为决策树分类器绘制 2 个以上的特征
- selenium-chromedriver - 使用 Chrome 驱动程序的 C# Selenium 代理身份验证
- python - 在其他功能中导入模块
- swift - 旋转光照环境内容 ARKit 和 SceneKit
- android - 安装引用库返回数据 utm_source=(not%20set)&utm_medium=(not%20set)?我怎样才能得到网址中提到的确切参数。?
- json - 带有变量的 JSON 对象到 PostgreSQL