嗨,我正在尝试更好地理解 angularJs watch 功能 为此,我制作了以下垃圾箱 enter link description here 其中包含一 block watch 。 第一次正确执行 watch 时,我可以看到旧值和新值。 第二次我在输入框中输入数字和字符串时,我没有看到记录的旧值和新值
$scope.$watch(function(theScope){
console.log(typeof theScope.price ==='number'); //logs true
if(typeof theScope.price ==='number'){
return theScope;
}else{
return false
}
},function(oldValue,newValue){
console.log('old:'+oldValue);
console.log('new:'+newValue);
});
最佳答案
一些事情。如果你想在 watch 中使用函数语法,可以这样写:
var app = angular.module('app',[]);
app.controller('MainController',['$scope',
function($scope){
$scope.message =20;
$scope.$watch(function($scope){
console.log(typeof $scope.message ==='number');
return $scope.message;
},function(oldValue,newValue){
console.log('old:'+oldValue);
console.log('new:'+newValue);
});
}
]);
此外,您在 html 中绑定(bind)了 message
,但在 watch 中使用了 price
。另外,您使用的是 theScope
,它实际上并未用于别名 $scope
。
将该代码粘贴到您的垃圾箱中,它应该可以工作。
关于javascript - 比较 $watch 函数内的基本类型时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36963378/