我正在制定一个指令,我通过将ng-show硬编码到form.birthdate.$touched && form.birthdate.$error.required
来进行表单验证。在完成这项工作之后,我开始删除该字符串的一部分,我将输入的name
硬编码为birthdate
。请参阅下面的代码,其中我有两个带有this field is required
消息的跨度。底部有效,顶部有效。如果我在HTML元素面板中查看它们看起来相同,所以看起来它应该可以工作但是事情没有被正确绑定。知道如何解决这个问题吗?
angular.module('MyModule').directive('vrDatepicker', function() {
return {
scope: {
dateModel: '='
},
link: function(scope, element, attrs, ctrls) {
scope.id = attrs.id;
scope.name = attrs.name;
scope.required = attrs.required;
scope.form = ctrls[0];
},
controller: ['$scope', function($scope) {
// Removed b/c it doesn't matter
}],
template: '<p class="input-group">\
<input type="text" \
class="form-control"\
datepicker-popup="MMM d, yyyy"\
ng-model="dateModel"\
is-open="opened"\
show-weeks="false"\
close-text="Close" />\
<span class="input-group-btn">\
<button type="button"\
class="btn btn-default"\
ng-click="open($event)">\
<i class="glyphicon glyphicon-calendar"></i>\
</button>\
</span>\
<span ng-show="form[\'{{name}}\'].$touched && form[\'{{name}}\'].$error.required" class="text-danger">This field is required</span>\ // ### This one doesn't work
<span ng-show="form.birthdate.$touched && form.birthdate.$error.required" class="text-danger">This field is required</span>'\ // ### This one works
</p>'
}
});
答案 0 :(得分:1)
这应该有效
<span ng-show="form[name].$touched && form[name].$error.required" class="text-danger">This field is required</span>
分配给ng-show
的字符串中的所有内容都将进行插值,因此您不需要所有额外的语法。