Angularjs: how to make input[text] ngModel delay valued while typing

Stiger

I have a textbox with ngModel binding, like this:

<input type="text" ng-model="typing" />

and value of this texbox

value: {{ typing }}

I want the model delay to update value while i'm typing. Maybe if I stop type in 500ms, the model will update all value (all things I typed in textbox). I make some google but no luck. Anyong has any idea? please help.

EDIT

This Angularjs: input[text] ngChange fires while the value is changing doesn't give solution for my case. It bring solution update value after blur, but I want the value update after stop typing, not blur textbox.

EDIT 2 (Answers)

With angular version 1.4, directive ngModelOptions is useful in my case. I can write like this <input ng-model="typing" ng-model-options="{ updateOn: 'default', debounce: {'default': 500, 'blur': 0} }" /> to delay update value to model 500ms in default and update immediately if lost focus.

Peter

The tidiest way to handle this is probably to write a directive which wraps up the <input> element and adds the delaying behaviour. Here is a directive I wrote for the same purpose:

angular.module('MyModule')
    .directive('easedInput', function($timeout) {
        return {
            restrict: 'E',
            template: '<div><input class="{{externalClass}} my-eased-input" type="text" ng-model="currentInputValue" ng-change="update()" placeholder="{{placeholder}}"/></div>',
            scope: {
                value: '=',
                timeout: '@',
                placeholder: '@',
                externalClass: '@class'
            },
            transclude: true,
            link: function ($scope) {
                $scope.timeout = parseInt($scope.timeout);
                $scope.update = function () {
                    if ($scope.pendingPromise) { $timeout.cancel($scope.pendingPromise); }
                    $scope.pendingPromise = $timeout(function () { 
                        $scope.value = $scope.currentInputValue;
                    }, $scope.timeout);
                };
            }
        }
    });

This directive would be called in your HTML like so:

<eased-input value="myValue" timeout="500" placeholder="Please enter text..." />

Dissecting the directive:

Timeout Service

This directive uses angular's $timeout service to handle timing: it is an injectable, mockable, idiomatic alternative to calling setTimeout. This service is injected in the directive constructor.

Attributes

The directive accepts three attributes: value, timeout and placeholder.

The value attribute here binds to a variable on the scope of the controller which owns the enclosing 'context'. In this case it binds to myValue, i.e. to $scope.myValue on whichever controller is in charge of this code. It has a two-way binding, denoted by the '=' entry in the scope property of the directive. This means that when this directive updates value, the change is propagated up to the controller which owns the directive; hence, $scope.myValue will change when value is changed inside the directive.

The timeout and placeholder attributes have one-way bindings: the directive reads their values from the attributes but does not alter them. They are effectively configuration values.

HTML Template

The template property on the directive shows the HTML which will be generated in its place once Angular compiles and links it. It's basically just an input element with some special and not-so-special attributes. The value in the input box is bound to the currentInputValue variable on the directive's $scope via ng-model. The change event on the input box is bound to the update function on the directive's $scope via the ng-change directive.

Link function

The guts of the process lie in the link function on the directive: we define an update method. As stated above, this method is bound to the change event of the input box within the directive's HTML template. Thus, every time the user changes the input in the box, update is called.

This method uses the $timeout service. It tells the $timeout service to wait for timeout milliseconds, then to apply a callback which sets $scope.value = $scope.currentInputValue. This is similar to calling setTimeout(function () {$scope.value = $scope.currentInputValue}, timeout).

The $timeout call returns a promise. We are able to cancel a promise p produced by $timeout which is waiting to execute by calling $timeout.cancel(p). This is what update does in its first line: if we have a promise from a previous change event, we cancel it before creating a new one. This means that if we have e.g. a 500ms timeout, and update gets called twice, with the calls 400ms apart, we will only have one promise waiting to fire.

Overall result

The promise, when resolved, sets $scope.value = currentInputValue; i.e. it sets the 'outwardly visible' value property to have the value of the contents of the input box. value will only change -- and external controllers will only see value change -- after a quiescent period of timeout milliseconds, which I believe is the behaviour you were after.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

How do I disable the touchpad while I'm typing?

분류에서Dev

AngularJs Error: [ngModel:nonassign]

분류에서Dev

Find and replace while typing command

분류에서Dev

Angularjs-ngModel 확장

분류에서Dev

How can I disable my touchpad/prevent accidental clicking while typing on Fedora 24?

분류에서Dev

How to allow moving the cursor while typing with xserver-xorg-input-libinput installed?

분류에서Dev

How to load a new page with AngularJS when a user start typing in an input box

분류에서Dev

How to update p:inputText from backing bean?

분류에서Dev

How to make a window transparent while moving it

분류에서Dev

AngularJS hide div after delay

분류에서Dev

ngModel의 AngularJS 형식 통화

분류에서Dev

How to put together 4 while loops of triangles to make a "diamond"?

분류에서Dev

AngularJS : ngModel로 여러 요소 바인딩

분류에서Dev

Angularjs ngModel 타이핑 상태 지시어

분류에서Dev

AngularJS orderBy same property as ngModel throws $digest error

분류에서Dev

Asterisk: Make IVR to say numbers during user typing

분류에서Dev

ngModel make datePicker 오늘 날짜 반환 null

분류에서Dev

How to get simulate Keyboard typing using python

분류에서Dev

WAITFOR DELAY doesn't act separately within each WHILE loop

분류에서Dev

angularjs this is undefined while using $.proxy

분류에서Dev

How to make an element correctly reset its state and pass props while focusing on the input

분류에서Dev

Autoclose Modal Window? How to make modal window automatically close after a while?

분류에서Dev

How to make image upload directly while choosing image rather than pressing upload button in JQuery

분류에서Dev

How can I make “ls” show dotfiles first while staying case-insensitive?

분류에서Dev

How to make requests to a local Rails app from a local AngularJS app running on a different port?

분류에서Dev

How do I add a delay to the mouseover function?

분류에서Dev

How to delay response until POST payload is validated

분류에서Dev

how to run script on remote machine with delay

분류에서Dev

데이터로 ngModel 초기화-AngularJS Bootstrap BS-select

Related 관련 기사

  1. 1

    How do I disable the touchpad while I'm typing?

  2. 2

    AngularJs Error: [ngModel:nonassign]

  3. 3

    Find and replace while typing command

  4. 4

    Angularjs-ngModel 확장

  5. 5

    How can I disable my touchpad/prevent accidental clicking while typing on Fedora 24?

  6. 6

    How to allow moving the cursor while typing with xserver-xorg-input-libinput installed?

  7. 7

    How to load a new page with AngularJS when a user start typing in an input box

  8. 8

    How to update p:inputText from backing bean?

  9. 9

    How to make a window transparent while moving it

  10. 10

    AngularJS hide div after delay

  11. 11

    ngModel의 AngularJS 형식 통화

  12. 12

    How to put together 4 while loops of triangles to make a "diamond"?

  13. 13

    AngularJS : ngModel로 여러 요소 바인딩

  14. 14

    Angularjs ngModel 타이핑 상태 지시어

  15. 15

    AngularJS orderBy same property as ngModel throws $digest error

  16. 16

    Asterisk: Make IVR to say numbers during user typing

  17. 17

    ngModel make datePicker 오늘 날짜 반환 null

  18. 18

    How to get simulate Keyboard typing using python

  19. 19

    WAITFOR DELAY doesn't act separately within each WHILE loop

  20. 20

    angularjs this is undefined while using $.proxy

  21. 21

    How to make an element correctly reset its state and pass props while focusing on the input

  22. 22

    Autoclose Modal Window? How to make modal window automatically close after a while?

  23. 23

    How to make image upload directly while choosing image rather than pressing upload button in JQuery

  24. 24

    How can I make “ls” show dotfiles first while staying case-insensitive?

  25. 25

    How to make requests to a local Rails app from a local AngularJS app running on a different port?

  26. 26

    How do I add a delay to the mouseover function?

  27. 27

    How to delay response until POST payload is validated

  28. 28

    how to run script on remote machine with delay

  29. 29

    데이터로 ngModel 초기화-AngularJS Bootstrap BS-select

뜨겁다태그

보관