【发布时间】:2015-09-12 17:34:01
【问题描述】:
我决定编写一个自定义指令来帮助我验证我的输入框。这个想法是我将我的新花哨nx-validate 指令添加到引导程序div.form-group,它会检查我的<input/> 是$dirty 还是$invalid,并根据需要应用.has-success 或.has-error 类.
出于某种奇怪的原因,我的指令在正常情况下完美运行,但添加的 ng-class 在 ui-bootstrap 模式中被完全忽略。
模态和表单中的相同代码
<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);
}
}
}
});
在 plunker 上查看:http://plnkr.co/edit/AjvNi5e6hmXcTgpXgTlH?
【问题讨论】:
-
将您的按钮放入表单中。当我在 plunker 示例中这样做时对我有用。
标签: javascript angularjs html twitter-bootstrap angularjs-directive