简体   繁体   中英

Angular directive's element

I have this directive:

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();
              });
            })
          }
        }
      }

Why is jQuery('.dnd').first() a different object than jQuery(element) ? They have different contexts and my jQuery plugin can only work with the first option.

jQuery(element) returns a jQuery wrapper of the element where the directive is being used. jQuery('.dndComponent').first() returns the first element with that class.

Assuming the directive is being only used once (do not rely on this), the selector is returning a child of element , element is the parent of '.dndComponent';

===

Consider also doing $(element).find('.dndComponent') because this way you can use your directive N times and it will always work, otherwise it will always return the .dndComponent of the first directive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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