简体   繁体   English

如何从角度的自定义窗体控件指令获取a的父窗体?

[英]How to get the parent form of a from a custom form control directive in angular?

Usually, validating forms in angular is done like this: 通常,以角度验证表单是这样的:

<form name="form">
  <input name="fruit" ng-model="ctrl.fruit" required>
  <span class="error" ng-show="form.fruit.$error.required">
    Fruit is required.
  </span>
</form>

The thing is that I have multiple forms some of which have similar fields, so I want to refactor some of this logic into a directive: 问题是我有多种形式,其中一些具有相似的字段,所以我想将一些逻辑重构为一个指令:

<form name="form1">
   <fruit-input></fruit-input>
</form>

<form name="form2">
   <fruit-input></fruit-input>
</form>

The problem is that the logic to display or hide the field error message requires the template to have access to the form to evaluate the condition form.fruit.$error.required . 问题是显示或隐藏字段错误消息的逻辑要求模板有权访问表单以评估条件form.fruit.$error.required But my fruitInput directive needs to work regardless of the form where it's inserted. 但是我的fruitInput指令需要工作,无论它插入的形式如何。

Is there a way for the directive to identify its parent form so I can use it in its (isolated) scope to show/hide the error message? 有没有办法让指令识别其父表单,以便我可以在其(隔离的)作用域中使用它来显示/隐藏错误消息?

Edit (due to a response questioning the usefulness of the question): Evidently the example is simplified. 编辑 (由于回答询问问题的有用性):显然,该示例已经简化。

In reality, a field on the form may have many of the following: a label, a help text, tooltip on hover, links to documentation, the control itself, all the different validation messages for the different validation conditions. 实际上,表单上的字段可能包含以下内容:标签,帮助文本,悬停工具提示,文档链接,控件本身,不同验证条件的所有不同验证消息。 One of such controls can easily be 20 lines of code and be used in 4~5 different places. 其中一个控件很容易就是20行代码,可以在4~5个不同的地方使用。 So it's worth refactoring it. 所以值得重构它。

Try this directive: 试试这个指令:

app.directive("fruitInput",function(){
  return {
    restrict:"E",
    template:'<input name="fruit" ng-model="ctrl.fruit" required> ' +
     ' <span class="error" ng-show="form.fruit.$error.required"> ' + //form here is the parent form resolved dynamically and saved in the scope as a property
     '  Fruit is required. ' +
     ' </span>',
     scope:{},
     require:"^form", //inject parent form as the forth parameter to the link function
     link:function (scope,element,attrs,form){
       scope.form = form; //save parent form
     }
  }
})

DEMO DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM