[英]angular custom validation directive does not show error on keyup event
我創建了一個用於驗證的角度指令,即使用輸入類型文本的模板,綁定了一個鍵輸入事件,在該事件中驗證輸入字段,僅使用ng-show打印錯誤消息,兩次鍵輸入后打印事件發生,但是在控制台中顯示了確切的錯誤,請幫助我解決此問題,將我的代碼粘貼到我的代碼鏈接中
var app = angular.module('myApp',[]);
app.directive('markdownEditor', function () {
return {
restrict: 'EA',
scope: {
ngModel: "="
},
require:'ngModel',
template:
'<input type="text" ng-model="foo" required/>',
link:function(scope,ele,attr,ctrl){
ele.bind("keyup",function(){
var reg=/[0-9!@#$%^&*_(=+^\(*\)\-\{:<>?|;',\/\[\]\"\})]/;
var y=scope.foo;
console.log(y);
if(reg.test(y)){
ctrl.$setValidity('c',false);
console.debug("not ok");
}
else{
ctrl.$setValidity('c',true);
console.debug("ok");
}
});
}
} ;
});
app.controller('DemoCtrl', function ($scope) {
});
您正在從Angular外部更新角度出價。 Angular不會為此類更改運行摘要周期。 在這種情況下,您要從自定義事件中更新作用域變量,這不會使Angular摘要系統與UI上已更新的內容緊密相關,因此摘要周期不會被觸發。
您需要手動啟動摘要循環以更新綁定。
scope.$apply()
更好的是,您還可以在此處使用需要regx值的ng-pattern
指令,當對regx不滿意時,它將ng-invalid-pattern
類添加到該元素。 在此基礎上,您可以添加CSS規則。
另外@paul trone建議使用$validators
,這也是一個不錯的選擇。
你為什么不嘗試使用內置的ngModelController $驗證器的管道來驗證,它會更新ng-valid-
/ ng-invalid-
自動類:
...
// in the directive link function
ctrl.$validators.c = function(input) {
return reg.test(input);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.