angularJS $watch $timeout 使用心得

<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记录一次修改次数



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值