为什么在单击按钮时未调用以下示例$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
};
}
};
});
答案 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();
});
});
}
}
});