我如何才能仅当用户完成键入时才调用angularjs ngChange处理程序 [英] How can I make angularjs ngChange handler be called only when user finishes typing

查看:81
本文介绍了我如何才能仅当用户完成键入时才调用angularjs ngChange处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 input 字段,我想在其中应用 ngChange 的变体。

I have an input field, where I want to apply the variant of ngChange.

input 字段是一种与ajax调用绑定的方法,当用户更改输入时,服务器端将处理数据,但是,我不想经常打这个电话。

The input field is sort of binding with an ajax call, when user changes the input, the server side will process the data, however, I don't wanna make the call too often.

假设用户要输入一个真正的字符串,我希望仅在用户完成将要键入的单词后才能进行呼叫。
不过,我不想使用诸如模糊这样的事件。有什么比 setTimeout 更好的方法呢?

Say the user wanna input a really string, I want the call be made only after user finishes the word he is about to type. Nevertheless, I don't wanna use event such as blur. What would be a better way to implement this, rather than setTimeout?

推荐答案

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

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}" />

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

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

在您的后备控制器/范围内

In your backing controller/scope

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

然后您的 taskToDo 仅在1000毫秒不变后运行。

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

这篇关于我如何才能仅当用户完成键入时才调用angularjs ngChange处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆