Javascript 有没有更简单的方法可以检查角度表的预期变化?
我正在使用以下代码:Javascript 有没有更简单的方法可以检查角度表的预期变化?,javascript,angularjs,Javascript,Angularjs,我正在使用以下代码: $scope.$watch('option.sTest', function (newValue, oldValue) { if (newValue !== undefined && newValue !== null && newValue !== oldValue) { } }); 这样做会使我的代码看起来臃肿不堪。有人对我如何以另一种方
$scope.$watch('option.sTest', function (newValue, oldValue) {
if (newValue !== undefined &&
newValue !== null &&
newValue !== oldValue) {
}
});
这样做会使我的代码看起来臃肿不堪。有人对我如何以另一种方式实施这些检查有什么建议吗?请注意,newValue或oldValue的0
值是有效的,因此我不能这样检查:
$scope.$watch('option.sTest', function (newValue, oldValue) {
if (newValue && oldValue &&
newValue !== oldValue) {
}
});
就我个人而言,这不会让我太烦恼,但是如果你发现自己到处都在使用这种模式,那么你可以编写一个函数
function isChangedRealValue(newValue, oldValue) {
return (newValue !== undefined && newValue !== null && newValue !== oldValue)
}
然后在代码中:
$scope.$watch('option.sTest', function (newValue, oldValue) {
if (isChangedRealValue(newValue, oldValue) {
// code goes here
}
});
如果确实要将其编码为更稀疏的线,可以执行以下操作:
if (~[undefined,null,oldValue].indexOf(newValue)) {
}
我不明白为什么您需要检查未定义或空值-这些不应该是您需要在watch listener中处理的情况。尝试:
$scope.$watch('option.sTest', function (newValue, oldValue) {
if (typeof newValue !== "undefined" && newValue !== null){
}
});
$watch在
newValue
不等于oldValue
时激发,因此我们不需要检查newValue!==oldValue
为什么在代码中“任何地方”都需要它们?一旦你有了一个手表,它就会监听对变量的任何修改,并在变量更改时执行函数。因为我有很多“无处不在”的选择列表,我需要监视用户何时更改值。undefined===undefined and null==null,所以如果你事后检查是否相等,就不需要同时检查这两个值。我不知道你为什么需要这张支票。编辑:看起来你已经删除了这些。在这一点上,代码与您的其他建议基本相同。我想如果没有上下文,我并不真正理解您的目的,但是对于选择列表,跟踪更改的另一种方法是将每个选择列表绑定到单独的ng更改函数(或根据您的目的绑定到同一个),然后检查您的ng模型作用域变量(理论上不能为null | |未定义)并相应地处理它。if(newValue!=0&&newValue&&newValue!==oldValue){}
除非选中空字符串值,“”