为什么在 AngularJS 中模型更改时不调用 ngModel 的 $render? [英] Why ngModel's $render is not called when the model changes in AngularJS?

查看:21
本文介绍了为什么在 AngularJS 中模型更改时不调用 ngModel 的 $render?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

演示

为什么在下面的例子中$render在按钮被点击时没有被调用?

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

推荐答案

input 指令在您的指令之后运行,因此它的 $render 函数正在取代您的指令.

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

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

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

您的 $render 将优先,您会看到警报被调用.

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

这篇关于为什么在 AngularJS 中模型更改时不调用 ngModel 的 $render?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆