AngularJS 嵌套指令深度

AngularJS nested directives depth

我正在寻找一种标记嵌套指令深度的方法。 假设我们有一个 item-container 和一个 ch-item,我将它们嵌套了几次 像这样:

  <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>

有没有办法像这样在不附加任何东西的情况下标记深度?

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

我用这个例子准备了一个 plunker : http://plnkr.co/edit/zC0XCeWJttroAX99Qc6i?p=preview

是否可以将变量 "down" 传递给元素?

一个解决方案是计算每个范围的 $parent 迭代次数:这为您提供了相对于 $rootScope.

范围的深度

这是一个实现:http://plnkr.co/edit/jDfqB1KnFa7oDHMfVhri?p=preview

共享服务是:

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