【问题标题】:getting the name of the form tag from an HTML element within a directive从指令中的 HTML 元素获取表单标签的名称
【发布时间】:2017-11-14 15:16:32
【问题描述】:

我正在获取 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;          
          }

【问题讨论】:

  • 你可以试试 element.closest(form).attr('name');

标签: angularjs


【解决方案1】:

以下代码应该为您获取validacion 元素所属表单的name 属性的值:

link: function (scope, element, attrs, ngModel) {
    console.log(element.closest('form').attr('name'));
  }

编辑如果项目中没有 jQuery,请改用 parent() 函数,前提是指令元素是 <form> 标记的直接子元素:

link: function (scope, element, attrs, ngModel) {
    console.log(element.parent().attr('name'));
  }

【讨论】:

  • ..closest 是 jquery 的函数吗? element.closest is not a function
  • 我不使用 jquery
  • element 是在 Angular 中使用 jQuery 的包装器。 docs.angularjs.org/api/ng/function/angular.element
  • 是的,如果 jQuery 不可用,angularJS 支持 jqLit​​e,它是 jQuery 的一个子集。 closest 似乎在 jqLit​​e 中不可用,所以要么使用 jQuery,要么改用 parent()。查看我的更新答案
【解决方案2】:

你应该需要formCtrl:

require: '^form',

并在指令的链接函数中使用它:

link: function(scope, element, attrs, formCtrl) {
    console.log(formCtrl);
}

有关将表单传递给指令的完整详细信息,请参阅 Stackoverflow 解决的类似问题: Pass form to directive

编辑:使用 AngularJS 1.5.x,你有不同的语法(能够跳过链接功能),只是引用 https://stackoverflow.com/users/1021943/priidu-neemre 很好的答案,(参见上面提到的链接更多):

return {
  restrict : 'EA',
  require : {
    form : '^'
  },

【讨论】:

    猜你喜欢
    • 2012-03-16
    • 1970-01-01
    • 2011-07-17
    • 1970-01-01
    • 2011-03-15
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    相关资源
    最近更新 更多