我有一个嵌套的 AngularJS 表单,如下所示:
<form name="parentForm" ng-submit="submit()">
<input name="parentInput" type="text">
<ng-include src="childForm.html" ng-form="childForm"></ng-include>
<button type="submit">Submit</submit>
</form>
这是 childForm.html
<input name="childInput" type="text">
由于与问题无关的原因,我无法合并父表单和子表单 - 它们需要是两个单独的文件。
现在,当用户单击提交按钮时,验证将正确应用于parentForm 和childForm。但是,只有父表单的 $subscribed 标志设置为 true,这是有问题的,因为我使用它来触发某些错误消息的显示。我不希望子表单检查父表单是否已提交,因为它们是两个单独的文件。我想到的唯一选择是让 subform() 方法在子表单上调用 $setSubscribed() ,这很尴尬,因为现在父表单需要直接引用子表单。有没有更好的方法将子表单的 $subscribed 设置为 true?
作为 Meeker 解决方案的扩展,您可以实现$broadcast
通过向父表单添加监视来隐式地进行:
.directive('form', function() {
return {
restrict: 'E',
require: 'form',
link: function(scope, elem, attrs, formCtrl) {
scope.$watch(function() {
return formCtrl.$submitted;
}, function(submitted) {
submitted && scope.$broadcast('$submitted');
});
}
};
})
.directive('ngForm', function() {
return {
restrict: 'EA',
require: 'form',
link: function(scope, elem, attrs, formCtrl) {
scope.$on('$submitted', function() {
formCtrl.$setSubmitted();
});
}
};
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)