【问题标题】:Angular directive's elementAngular 指令的元素
【发布时间】:2017-02-08 11:11:01
【问题描述】:

我有这个指令:

function dndDirective($timeout) {

  return {
    template: '<div class="dndComponent"> Title: {{title}} </div>',
    scope: {
      title: '<'
    },
    compile: myCompile
  };

      function myCompile(tElement, tAttrs, transclude) {
        return {
          pre: function postLink($scope, element, attrs, transclude) {

            $scope.$watchGroup(['title'], function(newVals) {
              $timeout(function() {
                jQuery('.dndComponent').first().myPlugin();
                jQuery(element).myPlugin();
              });
            })
          }
        }
      }

为什么jQuery('.dnd').first()jQuery(element) 是不同的对象?它们有不同的上下文,我的 jQuery 插件只能使用第一个选项。

【问题讨论】:

  • postLink函数的第二个参数
  • jQuery('.dnd') 将在该类的页面中的任何位置找到第一个元素。除此之外还不够了解
  • 这不是解释什么是元素。什么是html?
  • ^^ 注意应该说jQuery('.dnd').first() 有问题
  • @JoeyWood html 在指令的声明 template 字段中

标签: javascript jquery angularjs angular-directive


【解决方案1】:

jQuery(element) 返回使用该指令的元素的 jQuery 包装器。 jQuery('.dndComponent').first() 返回该类的第一个元素。

假设指令只被使用一次(不要依赖这个),选择器返回一个element 的子级,element 是'.dndComponent' 的父级;

===

考虑也做 $(element).find('.dndComponent') 因为这样你可以使用你的指令 N 次并且它总是有效的,否则它总是返回第一个指令的 .dndComponent

【讨论】:

    猜你喜欢
    • 2013-10-17
    • 1970-01-01
    • 2020-03-17
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多