0

How do I get an array of all the elements which share a directive so I can iterate over them and have them do different things to each other?

I have a directive which is used on multiple elements, and depending on the attribute value of each directive which uses restrict: 'A', I need the directives to all talk to each other and effect each other in different ways within the link function.

I've tried using:

link : function(scope, elem, attr) {
    attr.forEach(function(e, i) {
        if(attr[i] === 'menu') {
            //do something
        } else if (attr[i] === 'scroll') {
            //do something else
        }
    });
}

but I get forEach as an undefined function. I've also tried a simple for loop, but both:

elem.length

and

attr.length

give me undefined.


Note that I don't want to use different directives with different logic because I need each element to actually do something specific to each other element.

I could just use jQuery to select the elements straight up, but that's less than ideal for several reasons.

mmm
  • 2,272
  • 3
  • 25
  • 41

2 Answers2

2

You create a service that you inject into every directive you want, then you can iterate over them.

That's how you share data across directive and across controllers.

EDIT

You can create a global array that holds all your elements. Now you can iterate through them all. Here's a plunker.

app.directive('thing', function(){
  var elements = [];
  return {
    restrict: 'E',
    link: function(scope, element, attrs){
      element.text('hello');
      elements.push(element);
      console.log(elements);
    }
  };
});
GGhe
  • 663
  • 5
  • 17
  • There's nothing built into directives to allow you access to all elements that share a directive? – mmm Jan 05 '15 at 04:53
  • I believe [this post](http://stackoverflow.com/questions/20801843/angularjs-find-element-with-attribute) is what you're looking for. Look at the second answer. I have not found any documentation on a built in alternative. – GGhe Jan 05 '15 at 05:03
  • hmmm doesn't seem to be helpful... Obviously, I already know that you can access the element in your link function, but how does one get access to ALL the directive elements simultaneously in the link function without querying the dom? – mmm Jan 05 '15 at 05:08
0

Use jquery has-attribute selector:

var menuElements = $('[menu]');
var scrollElements = $('[scroll]');

And to iterate over the elements:

elements.each(function(index, elem) {
   ...
});
Michael Kang
  • 52,003
  • 16
  • 103
  • 135