角度ng变化延迟

时间:2014-10-19 02:29:16

标签: angularjs angularjs-directive angularjs-ng-repeat

我有一个输入,可以在更改时过滤ng-repeat列表。重复包含大量数据,需要几秒钟来过滤所有内容。在开始过滤过程之前,我希望它们延迟0.5秒。 创建此延迟的角度的正确方法是什么?

输入

 <input ng-model="xyz" ng-change="FilterByName()" />

重复

 <div ng-repeat"foo in bar">
      <p>{{foo.bar}}</p>
 </div>

过滤功能

 $scope.FilterByName = function () {
      //Filtering Stuff Here
 });

谢谢

4 个答案:

答案 0 :(得分:263)

AngularJS 1.3 +

从AngularJS 1.3开始,您可以利用debounce属性ngModelOptions提供的功能,轻松实现,而无需使用$timeout。这是一个例子:

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);
        };
    }
]);

- 或 -

<强> Check the Fiddle

在AngularJS 1.3之前

您必须使用$ timeout来添加延迟,并且可能使用$ timeout.cancel(previoustimeout)您可以取消任何先前的超时并运行新的超时(有助于防止执行过滤)在一个时间间隔内连续多次)

以下是一个例子:

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);
    }
});

答案 1 :(得分:18)

您可以使用$timeout添加延迟,并且可能使用$timeout.cancel(previoustimeout)您可以取消任何先前的超时并运行新的超时(有助于防止过滤在多个时间内执行时间间隔)

实施例: -

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);
  }
 });

<强> Plnkr

答案 2 :(得分:7)

我知道问题太旧了。但仍希望使用debouncing提供一种更快捷的方法来实现这一目标。

所以代码可以写成

<input ng-model="xyz" ng-change="FilterByName()" ng-model-options="{debounce: 500}"/>

去抖将以毫秒为单位。

答案 3 :(得分:0)

或者您可以使用指令&#39;预输入等待-MS =&#34; 1000&#34; &#39;来自angular-ui

<input 
   typeahead="name for name in filterWasChanged()"
   typeahead-wait-ms="1000"
   type="text" placeholder="search"
   class="form-control" style="text-align: right" 
   ng-model="templates.model.filters.name">