AngularJS: Watching for changes in ng-model and determine linked DOM element

Sometimes you want to watch for changes on your model within AngularJS and trigger an event if a model change occurs. For example, I needed to trigger a change event on the corresponding HTML DOM element whenever the model linked to the element changed. Here’s how to do it – using a $watch listener and a directive.

Simply watching for a model change is as easy as this:

$scope.something = 'abc';
$scope.$watch('something', function() {
    // TODO
});

However, you don’t get the corresponding DOM element with this code. So you better use this one:

app.directive('ngModel', function() {
    return {
        restrict: 'A',
        priority: 0,
        link: function(scope, element, attr) {
            scope.$watch(attr.ngModel, function(value) {
                element.trigger('change');
            });
        }
    };
});

Now you get the element. Unfortunately, you will probably encounter the following error: “Error: $rootScope:inprog – Action Already In Progress”

To avoid this, use a $timeout:

app.directive('ngModel', ['$timeout', function($timeout) {
    return {
        restrict: 'A',
        priority: 0,
        link: function(scope, element, attr) {
            scope.$watch(attr.ngModel, function(value) {
                $timeout(function() {
                    element.trigger('change');
                }, 0, false);
            });
        }
    };
}]);

3 thoughts on “AngularJS: Watching for changes in ng-model and determine linked DOM element”

  1. Am aflat aceasta pagina, dupa ce am cautat despre AngularJS: Watching for changes in ng-model and determine linked DOM element
    pe Google. Se pare ca informatia dvs e foarte valoroasa,
    mai ales ca am mai gasit aici si despre ora, ora exacta,
    lucruri interesante si folositoare. Mult succes
    in continuare!

Leave a Reply

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