50

我有一个input字段,我想在其中应用ngChange.

input字段类似于 ajax 调用的绑定,当用户更改输入时,服务器端将处理数据,但是,我不想经常调用。

假设用户想输入一个真正的字符串,我希望只有在用户完成他要输入的单词后才能进行调用。不过,我不想使用诸如模糊之类的事件。有什么更好的方法来实现这一点,而不是setTimeout

4

3 回答 3

106

ng-model-options在 Angular > 1.3 中使用

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

没有ng-model-options-- 在标记中:

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

在您的支持控制器/范围内

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.

于 2014-03-03T22:11:49.213 回答
38

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

于 2015-02-12T17:33:59.413 回答
1

编写您自己的指令 - 这只会根据您设置的条件在 myText 上运行命令

<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
                }
            });
        }
    }
})
于 2014-03-03T22:11:45.917 回答