<span style="font-size: 12px; font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">在使用angular时我们必不可少的会用到$watch ,angular在实现数据双向绑定时就已经再调用$watch了,</span><span style="font-size: 13.3333px; font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">$watch可以 监听任意模型ng-model,我们对该model修改时,就会调用相应的$watch进行监听 ,$timeout呢 有相当于angualr的定时器,我们把两个结合一下可以做出来 一个,监听input 且防抖动的效果,所谓防抖动,也就是数据延时提交,我们在input修改完之后,设置一定的延迟时间,等待用户再次输入 如果超出延迟时间用户还没有再次输入,我们就将数据提交。</span>
$scope.$watch('filterOptions', function (newVal, oldVal) {
if (newVal !== oldVal) {
if (timeout) $timeout.cancel(timeout); //如果当前时间已经有一个timeout在开启,那么先取消掉这个开启的timeout
timeout = $timeout(function() {
$scope.getPagedDataAsync('admin/bill/'+$stateParams.page+'?pageCount='+$scope.paginationConf.itemsPerPage,$scope.filterOptions);
}, 800);
}
}, true);
后来我发现我可以代替这个timeout功能,我自己写了一个类似的功能方法 供大家参考:
<!-- $watch 模型监控 -->
myApp.controller('myWatch',function($scope,$timeout){
$scope.name='nihao';
$scope.updated='-1';
var timeout='';
var executeTime='';
$scope.$watch('name',function(){
var currentTime = (new Date()).valueOf();
console.log("上次执行时间"+executeTime);
if ((currentTime-executeTime)<2000||executeTime=='') {
executeTime=currentTime;
return;
};
executeTime=currentTime;
$scope.updated++;
});
});
html
<!-- $watch 模型监控 --><br>模型监控<br>
<div ng-controller="myWatch">
<input ng-model="name" />
Name updated: {{updated}} times.
</div>
提交数据也就是,我这里用简单的update(修改次数)自增来代替 在页面上显示的效果 就是当用户输入一个字符,并且在两秒内不在做操作时,update记录一次修改次数