[英]AngularJS custom form validation directive doesn't work in my modal
我決定編寫一個自定義指令來幫助我驗證輸入框。 這個想法是我將新的nx-validate
指令添加到引導div.form-group
,它將檢查我的<input/>
是$dirty
還是$invalid
並應用.has-success
或.has-error
按要求上課。
出於某種奇怪的原因,我的指令在正常情況下可以正常運行,但是在ui-bootstrap模態中完全忽略了添加的ng-class
。
模態和形式相同的代碼
<form name="mainForm">
<div class="row">
<div nx-validate class="form-group has-feedback col-lg-6 col-md-6 col-xs-12">
<label class="control-label">Green if long enough, red if not</label>
<input type="text" id="name" class="form-control" ng-model="property.name" required="required" ng-minlength="5"/>
(once touched I do change colour - happy face)
</div>
</div>
我可愛的指令
nitro.directive("nxValidate", function($compile) {
return {
restrict: 'A',
priority: 2000,
compile: function(element) {
var node = element;
while (node && node[0].tagName != 'FORM') {
console.log (node[0].tagName)
node = node.parent();
}
if (!node) console.error("No form node as parent");
var formName = node.attr("name");
if (!formName) console.error("Form needs a name attribute");
var label = element.find("label");
var input = element.find("input");
var inputId = input.attr("id")
if (!label.attr("for")) {
label.attr("for", inputId);
}
if (!input.attr("name")) {
input.attr("name", inputId);
}
if (!input.attr("placeholder")) {
input.attr("placeholder", label.html());
}
element.attr("ng-class", "{'has-error' : " + formName + "." + inputId + ".$invalid && " + formName + "." + inputId + ".$touched, 'has-success' : " + formName + "." + inputId + ".$valid && " + formName + "." + inputId + ".$touched}");
element.removeAttr("nx-validate");
var fn = $compile(element);
return function($scope) {
fn($scope);
}
}
}
});
在插件上檢查一下: http ://plnkr.co/edit/AjvNi5e6hmXcTgpXgTlH嗎?
我建議您使用的最簡單方法是,可以通過在這些字段上使用watch來放置這些類,該watcher
在編譯DOM后將位於postlink
函數內
return function($scope, element) {
fn($scope);
$scope.$watch(function(){
return $scope.modalForm.name.$invalid && $scope.modalForm.name.$touched;
}, function(newVal){
if(newVal)
element.addClass('has-error');
else
element.removeClass('has-error');
})
$scope.$watch(function(){
return $scope.modalForm.name.$valid && $scope.modalForm.name.$touched;
}, function(newVal){
if(newVal)
element.addClass('has-success');
else
element.removeClass('has-success');
})
}
更新
實際的更好方法是代替編譯來自compile的元素,我們需要$compile
來自link
函數本身的元素。 使用$compile
在鏈接fn中編譯DOM的原因是我們的ng-class
屬性確實包含范圍變量,如myForm.name.$invalid
,因此,當我們$compile
編譯函數的DOM時,它們不評估值myForm.name.$invalid
變量的值,因為編譯無法訪問范圍,並且將始終是undefined
或blank
。 因此,盡管在link
內編譯DOM將具有不包含myForm.name.$invalid
所有范圍值,所以在使用指令范圍進行編譯后,您將獲得ng-class
指令綁定。
碼
compile: function(element) {
//..other code will be as is..
element.removeAttr("nx-validate");
//var fn = $compile(element); //remove this line from compile fn
return function($scope, element) {
//fn($scope);
$compile(element)($scope); //added in postLink to compile dom to get binding working
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.