【问题标题】:How can I get the name of a form in my directive?如何在我的指令中获取表单的名称?
【发布时间】:2017-11-14 02:57:12
【问题描述】:

我正在获取 ngModel 名称,但我还想获取带有“validacion”指令的元素所属的表单名称。

我严格需要获取 HTML 元素所属的表单的名称。我可以有几种形式,所以我需要一个动态的解决方案。非常感谢你

.directive('validacion', function ($timeout,$rootScope,validacionCampos,$compile) {

      return {
          restrict: 'AE',
          require: 'ngModel',

          link: function (scope, element, attrs, ngModel) {
                  if (!ngModel){
                          console.log("no hay modal")
                  return;          
          }

【问题讨论】:

    标签: javascript angularjs angularjs-ng-form


    【解决方案1】:

    您可以使用ng-form 以纯AngularJS 方式获取表单名称,如下所示:

    <ng-form name="myForm">
       <input type="text" name="cityInput">
    </ng-form>
    

    在 JavaScript 中你可以打印:

      console.log($scope.myForm);
    

    【讨论】:

    • 我严格需要获取 HTML 元素所属的表单的名称。我可以有几种形式,所以我需要一个动态的解决方案。非常感谢。
    • 此解决方案满足您的问题要求。您尚未指定是否有多个表单以及如何访问它。从下次开始,请务必提供更多详细信息。
    • "如何在我的指令中获取表单的名称?"
    【解决方案2】:

    在链接功能中,您可以通过这种方式获取表单名称。

    var formName = element.find("ng-form").attr("name");
    

    【讨论】:

    • 感谢您的回答。我正在输入这个console.log(element.find("form")),结果如下:i.imgur.com/9PKodTM.jpg
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 2016-07-02
    • 1970-01-01
    相关资源
    最近更新 更多