Angularjs 如果newValue更改,则触发角度监视
我想基于重复中的其他值更改值。我做了一块手表,但问题是,如果我改变手表内的新值,手表会再次被触发 有没有办法解决这个问题 我的手表:Angularjs 如果newValue更改,则触发角度监视,angularjs,angularjs-ng-repeat,watch,Angularjs,Angularjs Ng Repeat,Watch,我想基于重复中的其他值更改值。我做了一块手表,但问题是,如果我改变手表内的新值,手表会再次被触发 有没有办法解决这个问题 我的手表: $scope.$watch('objlist', function(newValue, oldValue) { $scope.counter += 1; for (var count = 0; count < newValue.length; ++count) { if (typeof newValue[count] != "u
$scope.$watch('objlist', function(newValue, oldValue) {
$scope.counter += 1;
for (var count = 0; count < newValue.length; ++count) {
if (typeof newValue[count] != "undefined" && (typeof oldValue == "undefined" || newValue[count].value1 != oldValue[count].value1)) {
newValue[count].value3 = newValue[count].value1 * newValue[count].value2;
newValue[count].value3 = Number(newValue[count].value3).toFixed(2);
}
if (typeof newValue[count] != "undefined" && (typeof oldValue == "undefined" || newValue[count].value3 != oldValue[count].value3)) {
newValue[count].value1 = newValue[count].value3 / newValue[count].value2;
newValue[count].value1 = Number(newValue[count].value1).toFixed(2);
}
}
}, true);
我已经包括了一个plunker来告诉你我的意思
如您所见,如果更改字段1或3的值,它会自动将2添加到计数器中,并将两者设置为toFixed2。这使得编辑字段变得很困难
我们使用angular 1.2.25你可以在条件下使用小技巧 例如:
$scope.watchActivated = true;
$scope.$watch('objlist', function(newValue, oldValue) {
if ( $scope.watchActivated ) {
$scope.watchActivated = false;
$scope.counter += 1;
for (var count = 0; count < newValue.length; ++count) {
if (typeof newValue[count] != "undefined" && (typeof oldValue == "undefined" || newValue[count].value1 != oldValue[count].value1) )
{
newValue[count].value3 = newValue[count].value1 * newValue[count].value2;
newValue[count].value3 = Number(newValue[count].value3).toFixed(2);
}
if (typeof newValue[count] != "undefined" && (typeof oldValue == "undefined" || newValue[count].value3 != oldValue[count].value3) )
{
newValue[count].value1 = newValue[count].value3 / newValue[count].value2;
newValue[count].value1 = Number(newValue[count].value1).toFixed(2);
}
}
$scope.watchActivated = true;
}
}, true);
虽然很不优雅,但它应该可以工作。
小心,代码可能不好,我只是做了一个快速编辑。不幸的是,它不起作用。这是因为第二块手表在第一块完成之前不会运行,因此第二次激活的手表也始终为真。只需提示,但您可以替换typeof newValue[count]!=仅由newValue[count]未定义。它也应该这样做。测试未定义的对象与说false是一样的,因为在$watch中,您将最后一个参数视为true,这意味着watch是deep object watch。您不能更改正在监视的对象。他可以为列表中的每个元素添加一个监视,以分隔。如果他不知道元素的数量,当然不可用。元素的数量可以改变,所以这是不可能的unfortunatly@Chandermani我知道我会深入观察对象,但这是检测列表中对象属性变化所必需的。