我尝试扩展角度输入指令,并在输入有错误后自动显示附加的错误框。
<form name="form">
<input with-error show-error-if="form.input.$error.required" name="input" required/>
<!-- error directive should be appended here and only shown when errors -->
</form>
<!-- working directive -->
<error field-name="input" show-if="form.input.$error.required"></error>
因此该指令指定如下:
app.directive("withError", [
'$compile', function($compile) {
return {
restrict: "A",
replace: true,
scope: {
showErrorIf: "@"
},
link: function(scope, element, attrs) {
if (element.next().length) {
element.next().insertBefore(element);
}
var newElHtml = '<error field-name="' + attrs.name + '" show-if="{{ showErrorIf }}"></error>';
var newEl = angular.element(newElHtml);
newEl.insertAfter(element);
$compile(newEl)(scope);
}
}
}
]);
指定错误指令:
app.directive("error", [
function() {
var errorTemplate;
errorTemplate = '<div class="error" ng-show="$parent.{{ showIf }}">{{ errors[fieldName] }}</div>';
return {
restrict: "E",
replace: true,
scope: {
fieldName: "@",
showIf: "@"
},
template: errorTemplate,
controller: function($scope, errorTexts) {
$scope.errors = errorTexts;
}
}
}
]);
问题是附加指令不会隐藏或显示,具体取决于手动添加时是否有错误?