嗨,我正在努力更好地理解angularJs手表的功能为了做到这一点,我在这里输入了以下bin的链接描述其中包含一块手表。手表第一次正常运行时,我可以看到新旧价值。第二次在输入框中输入数字和字符串时,我没有看到记录的旧值和新值
$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);
});
一些事情。如果你想在手表中使用函数语法,可以这样写:
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中绑定到了message
,但在手表中使用了price
。此外,您使用的是theScope
,它实际上并没有用于别名$scope
。
把代码粘贴到你的垃圾桶里,它应该可以工作了。
您可以简单地对$watch
进行定价
$scope.$watch('price',function(oldValue,newValue){
if(typeof newValue =='number'){
console.log('old:'+oldValue);
console.log('new:'+newValue);
}
});
也将ng-model='message'
更改为ng-model='price'
小提琴