Angular指令元素

Angular directive's element

本文关键字:元素 指令 Angular      更新时间:2023-09-26

我有这样的指令:

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插件只能使用第一个选项。

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

假设该指令只被使用一次(不要依赖于此),选择器返回element的子节点,element是'.dndComponent'的父节点;

= = =

也考虑做$(element).find('. dndcomponent '),因为这样你可以使用你的指令N次,它将始终工作,否则它将始终返回第一个指令的.dndComponent