我想写一个指令,当input失去焦点的时候,如果输入的不是数字,更改输入框中的文字
现在打印出来的viewValue和modelValue看起来变化了,但输入框中没有改变,求指教
myApp.directive('isNum',function(){
return {
require: '?ngModel',
link: function(scope, element, attrs,ngModel) {
if(!ngModel)return;
ngModel.$render = function() {
element.html(ngModel.$viewValue || '');
};
element.on('blur',function(){
if(isNaN(ngModel.$viewValue)){
scope.$apply(read);
}
});
function read(){
ngModel.$setViewValue("请输入数字");
ngModel.$setValidity('isNum',false);
console.log(ngModel);
}
}
};
});
<input type="text" ng-model = "test" is-num/>
改变值之后需要调用ngModel.$render();重新渲染,然后这个问题就解决了