在自定义指令中使用link函数代替compile函数,并使用$setValidity方法来更改输入的验证状态。在模板中使用ngModel指令来捕获输入值。
以下是示例代码:
HTML:
JS:
app.directive('myCustomDirective', function() { return { require: 'ngModel', link: function(scope, elem, attr, ctrl) { // 定义验证模式 var pattern = /abc/;
// 在输入事件中进行验证
elem.on('input', function() {
var inputValue = elem.val();
var isValid = pattern.test(inputValue);
ctrl.$setValidity('myCustomDirective', isValid);
});
}
}; });