Bongo
Bongo

Reputation: 3153

AngularJS nested directives depth

I am searching for a way to mark the depth of nested directives. Lets say we have a item-container and a ch-item and I nest them a couple of times like this:

  <ch-item-container>
    <ch-item>
      <ch-item></ch-item>  
      <ch-item-container>
        <ch-item>
          End of tree
        </ch-item>
      </ch-item-container>
    </ch-item>
  </ch-item-container>

Is there a way to mark the depth without attaching something to it like this ?

<ch-item depth="0"></ch-item>  

I prepared a plunker with this example : http://plnkr.co/edit/zC0XCeWJttroAX99Qc6i?p=preview

Is it maybe possible to pass a variable "down" to the elements ?

Upvotes: 0

Views: 64

Answers (1)

floribon
floribon

Reputation: 19193

One solution would be to count the number of $parent iterations for every scope: this gives you the depth of a scope relatively to the $rootScope.

here is an implementation: http://plnkr.co/edit/jDfqB1KnFa7oDHMfVhri?p=preview

With a shared service being:

chItemModule.service('depth', function () {
  return function depth(scope, d) {
    d = d || 0;
    if (!scope.$parent) {
      return d;
    }
    return depth(scope.$parent, d + 1);
  }
});

Upvotes: 1

Related Questions