1

My AngularJS project needs a nested directive for layer and item.

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

And my JavaScript is like this.

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")
            }
        }
    }
]);

But the console.log("ok") does not populate in item directive.

5
  • can you give an example of expected output? Commented Jan 19, 2017 at 19:34
  • expected output is browser console writes "ok". Commented Jan 19, 2017 at 19:36
  • you used replace:true in 'layer' so it replaces the dom by <div> which does n't have anything to compile, so 'item' is never called. Commented Jan 19, 2017 at 19:44
  • I know replace:true changes own template with <div> but not inner directive. Does it wrong? Commented Jan 19, 2017 at 19:48
  • i would say, more precisely it repalces the "element" itself Commented Jan 19, 2017 at 19:53

1 Answer 1

1

You need to use the ng-transclude directive in the template to indicate where the transcluded content will be contained. Without this, the content will be discarded which is why you're not seeing the console.log message. Here is a working example that shows how to use 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>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.