角NG改变延迟 [英] Angular ng-change delay
问题描述
我有过滤对变化的NG-重复清单的投入。重复含有大量的数据,并且需要几秒钟通过一切进行过滤。我想他们是0.5秒的延时之前,我开始过滤过程。 什么是角正确的方式来创建这个延时?
I have an input which filters a ng-repeat list on change. The repeat contains a lot of data and takes a few seconds to filter through everything. I would like their to be 0.5 second delay before I start the filtering process. What is the correct way in angular to create this delay?
输入
<input ng-model="xyz" ng-change="FilterByName()" />
重复
<div ng-repeat"foo in bar">
<p>{{foo.bar}}</p>
</div>
过滤器功能
$scope.FilterByName = function () {
//Filtering Stuff Here
});
感谢
推荐答案
AngularJS 1.3 +
由于AngularJS 1.3你可以利用防抖动
ngModelOptions
提供了实现这一目标很容易,而无需使用 $超时
可言。这里有一个例子:
Since AngularJS 1.3 you can utilize the debounce
property ngModelOptions
provides to achieve that very easy without using $timeout
at all. Here's an example:
HTML
<div ng-app='app' ng-controller='Ctrl'>
<input type='text' placeholder='Type a name..'
ng-model='vm.name'
ng-model-options='{ debounce: 1000 }'
ng-change='vm.greet()'
/>
<p ng-bind='vm.greeting'></p>
</div>
JS:
angular.module('app', [])
.controller('Ctrl', [
'$scope',
'$log',
function($scope, $log){
var vm = $scope.vm = {};
vm.name = '';
vm.greeting = '';
vm.greet = function greet(){
vm.greeting = vm.name ? 'Hey, ' + vm.name + '!' : '';
$log.info(vm.greeting);
};
}
]);
- 或 -
-- OR --
Check the Fiddle
AngularJS 1.3之前
您将不得不使用$超时增加延迟,可能与使用$ timeout.cancel(previoustimeout),你可以取消任何previous超时并运行新的(帮助prevent滤波要consecutovely一个时间间隔内执行多次)
You'll have to use $timeout to add a delay and probably with the use of $timeout.cancel(previoustimeout) you can cancel any previous timeout and run the new one(helps to prevent the filtering to be executed multiple times consecutovely within a time interval)
下面是一个例子:
app.controller('MainCtrl', function($scope, $timeout) {
var _timeout;
//...
//...
$scope.FilterByName = function () {
if(_timeout){ //if there is already a timeout in process cancel it
$timeout.cancel(_timeout);
}
_timeout = $timeout(function(){
console.log('filtering');
_timeout = null;
},500);
}
});
这篇关于角NG改变延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!