0

I'm trying to create a method that reproduces the selector of angularjs directives:

// this method tries to apply a directive on: Attributes (A), Element/tags (E) , css class (C), Comments (M)
app.directive("myDirective",{restrict: 'AECM'})

My idea:

    var elements=[];

    if (restriction.indexOf('A')>=0) {
        var res=document.querySelectorAll("["+element+"]");
        res.length > 0 && ( elements = elements.concat(res));
    }

    if (restriction.indexOf('C')>=0) {
        var res=document.querySelectorAll("."+element);
        res.length > 0  && ( elements = elements.concat(res));
    }

    if (restriction.indexOf('E')>=0) {
        var res=document.querySelectorAll(element);
        res.length > 0  && ( elements = elements.concat(res));
    }

    // TODO: comments (M)

    return elements;

Is this the best way to do it? how angularjs handles it? i tried to check the angularjs code but didn't find anything.

  • I couldn´t find it in their code either. Still, be careful that you might be adding the same element multiple times with that code – juvian Oct 27 '16 at 14:32
  • this is where angular checks restrict: https://github.com/angular/angular.js/blob/master/src/ng/compile.js#L1064 and https://github.com/angular/angular.js/blob/master/src/ng/compile.js#L2946. – Claies Oct 27 '16 at 15:11
  • @Claies it's just a check , i cannot see where directive.restrict is used to select elements – Joseph Roy Oct 27 '16 at 15:16
  • @juvian thanks, i've structured in this way because directives seems to be applied on multiple elements if any – Joseph Roy Oct 27 '16 at 15:16
  • This is the view from a bit higher in the code chain: https://github.com/angular/angular.js/blob/master/src/ng/compile.js#L2104. – Claies Oct 27 '16 at 15:19
  • @JosephRoy I mean that if your restriction is AC and you have it as both attribute and class, you will add that element to elements twice – juvian Oct 27 '16 at 15:24

0 Answers0