AngularJS delayedModel directive

Jan 13, 2014 in AngularJS, directive, Javascript, Projects

ngModel directive allows to setup two-way data binding updating model if the value changes in the view, and other way around. Value gets updated immediately, however sometimes it's useful to trigger update action after some delay. In Angular 1.3 there is a built-in mechanism which allows you to delay ngModel synchronization or specify event associated with it (like onblur, for instance). The next custom directive does the trick allowing you to add arbitrary delay on model update.

Consider this simple snippet:

.directive('delayedModel', function() {
    return {
        scope: {
            model: '=delayedModel'
        },
        link: function(scope, element, attrs) {

            element.val(scope.model);

            scope.$watch('model', function(newVal, oldVal) {
                if (newVal !== oldVal) {
                    element.val(scope.model);        
                }
            });

            var timeout;
            element.on('keyup paste search', function() {
                clearTimeout(timeout);
                timeout = setTimeout(function() {
                    scope.model = element[0].value;
                    element.val(scope.model);
                    scope.$apply();
                }, attrs.delay || 500);
            });
        }
    };
});

Now we can use it to bind delayed models:

<input type="text" delayed-model="name" data-delay="500">
<div>{{name}}</div>

In this example value of the model name will update after 500 milliseconds. Very simple solution.

Here is the demo:

comments powered by Disqus