为什么在AngularJS中模型更改时不调用ngModel的$ render?

时间:2014-01-13 04:49:05

标签: angularjs angularjs-directive

DEMO

为什么在单击按钮时未调用以下示例$render

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

2 个答案:

答案 0 :(得分:33)

input指令在您的指令之后运行,因此$render函数正在替换您的指令。

将指令的优先级设置为大于0的值。例如:

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

您的$render将优先,您将看到您的提醒被调用。

答案 1 :(得分:1)

ngModel.$render中致电$render时,

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