How can I make angularjs ngChange handler be called only when user finishes typing

一个人想着一个人 提交于 2019-11-28 16:11:21

Use ng-model-options in Angular > 1.3

 <input type="text"
         ng-model="vm.searchTerm"
         ng-change="vm.search(vm.searchTerm)"
         ng-model-options="{debounce: 750}" />

Without ng-model-options -- In markup:

<input ng-change="inputChanged()">

In your backing controller/scope

var inputChangedPromise;
$scope.inputChanged = function(){
    if(inputChangedPromise){
        $timeout.cancel(inputChangedPromise);
    }
    inputChangedPromise = $timeout(taskToDo,1000);
}

Then your taskToDo will only run after 1000ms of no changes.

Adrien

As of Angular 1.3, you could use Angular ng-model-options directive

<input ng-change="inputChanged()" ng-model-options="{debounce:1000}">

Source: https://stackoverflow.com/a/26356084/1397994

Write your own directive- this will only run the commands on myText based on the conditions you set

<input my-change-directive type="text ng-model="myText" />

.directive('myChangeDirective',function() {
    return {
        require : 'ngModel',
        link : function($scope,$element,$attrs) {
            var stringTest = function(_string) {
                //test string here, return true
                //if you want to process it
            }
            $element.bind('change',function(e) { 
                if(stringTest($attrs.ngModel) === true) {
                    //make ajax call here
                    //run $scope.$apply() in ajax callback if scope is changed
                }
            });
        }
    }
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!