I decided to write a custom directive to help me validate my input boxes. The idea is that I add my new fancy nx-validate
directive to a bootstrap div.form-group
and it'll check whether my <input/>
is $dirty
or $invalid
and apply the .has-success
or .has-error
class as required.
For some odd reason, my directive works perfectly under normal circumstances, but the added ng-class
is completely ignored inside a ui-bootstrap modal.
Identical code in both the modal and the form
<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>
And my lovely directive
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);
}
}
}
});
Check it out on plunker: http://plnkr.co/edit/AjvNi5e6hmXcTgpXgTlH?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…