检查指令是否包含AngularJS中的子指令

时间:2018-02-05 15:21:08

标签: angularjs

有没有办法检查指令是否包含另一个指令?据我所知,在AngularJS中没有什么可以做的,你不能在父母中要求子指令。

我有两个指令,一个叫page-wrapper,另一个是content-wrapper,如下所示:

<md-content page-wrapper>
    <profiles $router="::$$router" class="ng-scope ng-isolate-scope">
        <page-content>
        </page-content>
    </profil-liste>
</md-content>

我要做的是检查page-wrapper指令是否在其子节点中包含page-content指令,如果没有,那么我应该引发一些异常。

我不想检查page-content是否在其父母的内部,我已经知道如何不符合我的要求。

编辑:

请注意我正在使用angular_1_router,因此page-content未在编译page-wrapper的阶段呈现,这就是page-wrapper所看到的情况链接功能:

innerHTML:"<profiles $router="::$$router" class="ng-scope"></profiles>"

因此,在DOM中搜索page-content对任何事情都无济于事。

我还尝试使用$timeout服务延迟它:

function PageWrapperPostLink(scope, element, attrs, controller) {
    $timeout(function(){
        console.log(element);
    });
}

哪个没用,包含page-content的页面还没有注入路由器。

1 个答案:

答案 0 :(得分:0)

如果您没有找到page-content指令,我不确定您想要发生什么,但这里有一些示例代码,说明如何从page-wrapper指令进行搜索以确定该情况

angular.module('app', [])
  .directive('pageWrapper', function() {
    return {
      restrict: 'A',
      link: function(scope, element, attrs) {
        var pageContent = element[0].querySelector('page-content');
        if (pageContent) {
          console.log('found');
        } else {
          console.log('not found');
        }
      }
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<div ng-app="app">
  <div>
    <md-content page-wrapper>
      <profiles $router="::$$router" class="ng-scope ng-isolate-scope">
        <page-content>
        </page-content>
      </profiles>
    </md-content>
  </div>
</div>

相关问题