AngularJS > Forms & Validations

Delaying model update in AngularJS

How to delay model updates in AngularJS?

In the previous post, we learnt how to attach custom trigger to update model. In this post, we shall learn how to delay model updates model after user action. This is done using ng-model-options directive with 'debounce: milliseconds' option.

In the <script> block, we have a PD object created with $scope whose properties will be set in the HTML blcok with the help of the ng-model directive of the input element.

    var app = angular.module("app", []);
    app.controller("CustomTriggerController", ["$scope", function ($scope) {
        $scope.PD = {};

<div ng-app="app" ng-controller="CustomTriggerController">
    <form name="myForm">
            Username: <input type="text" ng-model="PD.username" required
                             ng-model-options="{updateOn : 'blur', debounce : 400}" />

        Address: <input type="text" ng-model="PD.address" required
                        ng-model-options="{updateOn : 'default blur',
debounce : {default: 250, blur: 100}}" />
    <hr />
    <b>Username:</b> {{PD.username}} <br />
    <b>Address:</b> {{PD.address}}

In the HTML block, notice ng-model-options directive whose value is set with debounce option apart from updateOn trigger.

In case of Username, the model gets updated after .4 seconds of text box looses focus.

In case of Address, the model gets updated after .25 seconds while user is changing text box value or .10 seconds after user has shifted the focus.


Delay update in AngularJS

 Views: 2059 | Post Order: 55

Write for us