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

倾然丶 夕夏残阳落幕 提交于 2019-12-04 15:59:57

问题


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
      };
    } 
  };
}); 

回答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.




回答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();
            });
            });
        }
    }
});


来源:https://stackoverflow.com/questions/21084088/why-ngmodels-render-is-not-called-when-the-model-changes-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!