Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

javascript - Can I debounce or throttle a watched <input> in AngularJS using _lodash?

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

});

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.

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use ngModelOptions in Angular 1.3.0

HTML:

<div ng-controller="Ctrl">
  <form name="userForm">
    Name:
    <input type="text" name="userName"
           ng-model="user.name"
           ng-model-options="{ debounce: 1000 }" />
    <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button><br />
  </form>
  <pre>user.name = <span ng-bind="user.name"></span></pre>
</div>

More Info: https://docs.angularjs.org/api/ng/directive/ngModelOptions


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...