我正在创建一个自定义指令,以通用方式显示表单错误(使用ng-messages)。该指令将通过以下方式调用:
<show-errors form="login_form" field="email"></show-errors>
...
<show-errors form="login_form" field="password"></show-errors>
指令声明:
function showGenericErrors() {
return {
restrict: 'E',
templateUrl: 'views/error.dir.tmpl.html',
replace: true,
scope: {
form: '@',
field: '@'
},
transclude: true,
link: function (scope, element, attrs, ctrl, transclude) {
scope.theForm = scope.$parent[attrs.form];
transclude(scope, function (clone, scope) {
element.append(clone);
});
}
};
}
这是模板:
<div>
<!-- Here I can access form property via bracket notation -->
<!-- {{theForm[field].$blurred }} -->
<!-- But here I cannot use the same notation inside ng-if -->
<div class="error" ng-if="theForm[field].$blurred" ng-messages="theForm[field].$error" ng-messages-include="views/errors.html">
</div>
</div>
模板不起作用!
因为,我会在多种形式上使用这个指令&amp;字段,如何验证指令模板中的条件。或者有更好的方法来解决这个问题吗?
答案 0 :(得分:3)
<强>解决!强>
新指令:
function showErrors() {
return {
restrict: 'E',
templateUrl: 'views/error.dir.tmpl.html',
replace: true,
scope: {
form: '@',
field: '@'
},
link: function(scope, element, attrs, ctrl) {
scope.theForm = scope.$parent[attrs.form];
scope.formField = scope.theForm[attrs.field];
}
};
}
&#13;
新模板:
<div>
<div class="error" ng-if="formField.$blurred" ng-messages="formField.$error" ng-messages-include="views/errors.html">
</div>
</div>
&#13;