Immediate and non-immediate model updates in AngularJS

2 min read
Share:

In AngularJS, immediate model updates is a default behavior but if we want to persist value in the object after a certain time period has elapsed then we can achieve the same by using “debounce” object in “ng-model-options” directive, which is known as “non-immediate model updates”.

  1. Immediate Model updates

    [html]
    <div ng-app="MyApp">
    <input type="text" ng-model="message">
    <p>
    {{ message }}
    </p>
    </div>
    [/html]

    In the example above the value of “message” immediately updates itself (default behavior of AngularJS) on the change of value in the text box.

  2. Non-immediate model updates

    You can use “debounce” to delay the model update/validate with the “ng-model-options” directive.

    [html]
    <div ng-app="MyApp">
    <input type="text" ng-model="message" ng-model-options="{ debounce : 1000 }">
    <p>
    {{ message }}
    </p>
    </div>
    [/html]

    In the example above we added a directive “ng-model-options” in the textbox and then a key “debounce” in it with value “1000” ms. So now it will wait for 1 sec before updating its value according to the text in the box.

    We can also set custom debounce for each event using an object in “debounce”.

    [html]
    <div ng-app="MyApp">
    <input type="text" ng-model="message" ng-model-options="{ updateOn: ‘default blur’, debounce : {default: 1000, blur: 0} }">
    <p>
    {{ message }}
    </p>
    </div>
    [/html]

    In the example above value of “message” will update with a delay of 1 second from the change in the textbox or it will change immediately in case the textbox losses focus.

Hope this helps !!!

comments ( 1 )

Leave a Reply

Your email address will not be published. Required fields are marked *