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

查看:25
本文介绍了如何仅在用户完成输入时调用 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?

推荐答案

Use ng-model-options in Angular > 1.3

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 -- 在标记中:

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

那么你的 taskToDo 只会在 1000 毫秒没有变化后运行.

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

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

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