繁体   English   中英

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

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

通常,以角度验证表单是这样的:

<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>

问题是我有多种形式,其中一些具有相似的字段,所以我想将一些逻辑重构为一个指令:

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

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

问题是显示或隐藏字段错误消息的逻辑要求模板有权访问表单以评估条件form.fruit.$error.required 但是我的fruitInput指令需要工作,无论它插入的形式如何。

有没有办法让指令识别其父表单,以便我可以在其(隔离的)作用域中使用它来显示/隐藏错误消息?

编辑 (由于回答询问问题的有用性):显然,该示例已经简化。

实际上,表单上的字段可能包含以下内容:标签,帮助文本,悬停工具提示,文档链接,控件本身,不同验证条件的所有不同验证消息。 其中一个控件很容易就是20行代码,可以在4~5个不同的地方使用。 所以值得重构它。

试试这个指令:

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

暂无
暂无

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

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