我可以抖或者油门观看<输入>在AngularJS使用_lodash? [英] Can I debounce or throttle a watched <input> in AngularJS using _lodash?

查看:142
本文介绍了我可以抖或者油门观看<输入>在AngularJS使用_lodash?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有做在一个℃的观看以下;这势必$ scope.id 字段,输入过夜。每次输入字段值变化时,手表的功能得到执行:

I have the following which does a watch on an <input> field that's bound to $scope.id. Every time the input field value changes the watch function gets executed:

$scope.$watch("id", function (id) {

   // code that does something based on $scope.id

});

有没有一种方法我可以把超时在这个或反跳这跟_lodash从而使code
当用户正在改变的值上的每个键preSS不执行。

Is there a way I can put a timeout on this or debounce this with _lodash so that the code does not execute on each keypress while the user is changing the value.

我想是的
一秒的延迟,使得后用户停止键入一秒钟,然后
表内的code座运行。请注意,输入值是什么,可以在任何时间改变。例如我需要的功能,如果该值是被称为1或10或1000。这类似于与建议的搜索框工作在谷歌的方式什么的。如果999的用户类型,然后我需要的函数被调用。如果他删除了一个9所以它是99,那么我需要调用的函数。

What I would like is for a delay of one second so that after the user has stopped typing for one second then the code block inside the watch runs. Note that the input value is something that could change at any time. For example I need the function to be called if the value is "1" or "10" or "1000". This is something similar to the way the search box with suggestions works in Google. If the user types in 999 then I need the function to be called. If he deletes a 9 so it's 99 then I need the function to be called.

我有可用_lodash因此使用这可能是我需要最合适的解决方案。

I do have _lodash available so a solution that uses that might be the best fit for my needs.

推荐答案

是你在找什么?

$scope.$watch("id", _.debounce(function (id) {
    // Code that does something based on $scope.id
    // This code will be invoked after 1 second from the last time 'id' has changed.
}, 1000));

请注意,但是,如果你想改变该函数内部$范围,你应该把它包装 $范围。$申请(...)作为除非 _。去抖函数使用 $超时内部(如其中据我所知它不这样做)角将不知道的您在 $范围做了修改

Note, however, that if you want to change $scope inside that function you should wrap it $scope.$apply(...) as unless _.debounce function uses $timeout internally (which as far as I understand it doesn't do) Angular will not be aware of the changes you did on the $scope.

更新

至于更新的问题 - 是的,你需要来包装整个回调函数体

As to the updated question - yes you need to wrap the entire callback function body with

$ $范围适用于()

$scope.$watch("id", _.debounce(function (id) {
    // This code will be invoked after 1 second from the last time 'id' has changed.
    $scope.$apply(function(){
        // Code that does something based on $scope.id
    })
}, 1000));

这篇关于我可以抖或者油门观看&LT;输入&GT;在AngularJS使用_lodash?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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