AngularJS嵌套指令不访问子指令

时间:2017-01-19 19:31:10

标签: javascript angularjs

我的AngularJS项目需要图层项目的嵌套指令。

obj.toJSON

我的JavaScript就是这样。

<layer>
    <item>
    </item>
</layer>

但是angular.module('app', []); var app = angular.module('app'); app.directive('layer', [ function () { return { replace:true, transclude:true, template: "<div></div>", link:function(){ } } } ]); app.directive('item', [ function () { return { require:"^layer", template: "<div></div>", link: function(){ console.log("ok") } } } ]); 没有填充console.log("ok")指令。

1 个答案:

答案 0 :(得分:1)

您需要在模板中使用ng-transclude指令来指示转换内容的包含位置。如果没有这个,内容将被丢弃,这就是你没有看到console.log消息的原因。以下是一个展示如何使用transclusion的工作示例:

angular.module('app', [])
  .directive('layer', [
    function() {
      return {
        replace: true,
        transclude: true,
        template: "<div>layer<div ng-transclude></div></div>",
        link: function() {
          console.log('layer');
        }
      }
    }
  ])
  .directive('item', [
    function() {
      return {
        template: "<div>item</div>",
        link: function() {
          console.log("ok");
        }
      }
    }
  ]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<div ng-app="app">
  <layer>
    <item></item>
  </layer>
</div>