问题描述
我有一个输入,它在更改时过滤 ng-repeat 列表.重复包含大量数据,需要几秒钟来过滤所有内容.我希望它们在我开始过滤过程之前有 0.5 秒的延迟.产生这种延迟的正确角度是什么?
输入
重复
<p>{{foo.bar}}</p>
过滤功能
$scope.FilterByName = function () {//过滤这里的东西});
谢谢
AngularJS 1.3+
从 AngularJS 1.3 开始,您可以利用 debounce
属性 ngModelOptions
提供了在不使用 $timeout
的情况下非常容易地实现这一目标.举个例子:
HTML:
<input type='text' placeholder='Type a name..'ng-model='vm.name'ng-model-options='{ 去抖动:1000 }'ng-change='vm.greet()'/><p ng-bind='vm.greeting'></p>
JS:
angular.module('app', []).controller('Ctrl', ['$范围','$log',功能($范围,$日志){var vm = $scope.vm = {};vm.name = '';vm.greeting = '';vm.greet = 函数问候(){vm.greeting = vm.name ?'嘿,' + vm.name + '!':'';$log.info(vm.greeting);};}]);
-- 或 --
AngularJS 1.3 之前
您必须使用 $timeout 来添加延迟,并且可能使用 $timeout.cancel(previoustimeout) 您可以取消任何先前的超时并运行新的超时(有助于防止多次执行过滤在一个时间间隔内连续)
这是一个例子:
app.controller('MainCtrl', function($scope, $timeout) {变量_超时;//...//...$scope.FilterByName = function() {if(_timeout) {//如果进程已经超时,则取消它$timeout.cancel(_timeout);}_timeout = $timeout(function() {console.log('过滤');_超时=空;}, 500);}});
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
<input ng-model="xyz" ng-change="FilterByName()" />
Repeat
<div ng-repeat"foo in bar">
<p>{{foo.bar}}</p>
</div>
Filter Function
$scope.FilterByName = function () {
//Filtering Stuff Here
});
Thanks
AngularJS 1.3+
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 --
Before AngularJS 1.3
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)
Here is an example:
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-change 延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!