Why ngModel's $render is not called when the model changes in AngularJS?

All we need is an easy explanation of the problem, so here it is.

DEMO

Why in the following example $render is not called when the button is clicked?

<input type="text" ng-model="client.phoneNumber" phone-number>
<button ng-click="client.phoneNumber='1111111111'">Change phone number</button>
.directive("phoneNumber", function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
      ngModel.$render = function() {
        alert('rendering');   // This is not called
      };
    } 
  };
}); 

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

The input directive is running after your directive and thus it’s $render function is replacing yours.

Set your directive’s priority to something greater than 0. For instance:

.directive("phoneNumber", function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    priority: 1,
    link: function(scope, element, attrs, ngModel) {
      ngModel.$render = function() {
        alert('rendering');
      };
    } 
  };
});

And your $render will take precedence and you’ll see your alert is called.

Method 2

ngModel.$render is working, when calling $render in the $apply.

app.directive('changecase', function ($timeout) {
    return {
    restrict: 'A',
    require: 'ngModel',
    priority: 1,
    link: function (scope, element, attrs, ngModel) {
      
        //format text going to user (model to view)
        ngModel.$formatters.push(function(value) {
            return value.toUpperCase();
        });

        //format text from the user (view to model)
        ngModel.$parsers.push(function(value) {
            return value.toUpperCase();
        });

        element.on('blur keyup change', function() {
            scope.$apply(function(){
              ngModel.$setViewValue(ngModel.$modelValue);
              ngModel.$render();
            });
            });
        }
    }
});

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply