AngularJS - Find Element with attribute

前端 未结 3 1648
南方客
南方客 2020-12-23 10:05

I\'m new to AngularJS. I\'ve learned that I can find elements in the DOM using queries like the following:

var e = angular.element(document.querySelector(\'#         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-23 10:17

    Your use-case isn't clear. However, if you are certain that you need this to be based on the DOM, and not model-data, then this is a way for one directive to have a reference to all elements with another directive specified on them.

    The way is that the child directive can require the parent directive. The parent directive can expose a method that allows direct directive to register their element with the parent directive. Through this, the parent directive can access the child element(s). So if you have a template like:

    Then the directives can be coded like:

    app.directive('parentDirective', function($window) {
      return {
        controller: function($scope) {
          var registeredElements = [];
          this.registerElement = function(childElement) {
            registeredElements.push(childElement);
          }
        }
      };
    });
    
    app.directive('childDirective', function() {
      return {
        require: '^parentDirective',
        template: 'Child directive',
        link: function link(scope, iElement, iAttrs, parentController) {
          parentController.registerElement(iElement);
        }
       };
    });
    

    You can see this in action at http://plnkr.co/edit/7zUgNp2MV3wMyAUYxlkz?p=preview

提交回复
热议问题