1

I want to write an AngularJS directive such as

<my-directive>
    <inner-body>
        normal HTML and Angular constructs
    </inner-body>
</my-directive>

And should be converted as

<div class="group">
  <div> directive inserted text </div>
  <div class="groupBody">
      normal HTML and Angular constructs
  </div>
</div>

Basically, I want to have flexibility to write HTML inside inner-body. The directive will convert it to div and apply some attributes to this div.

Is it possible?

TIA.

1 Answer 1

1

Yes it's possible, use ngTransclude (ngTransclude)

Extract from AngularJS:

<script>
  angular.module('transcludeExample', [])
   .directive('pane', function(){
      return {
        restrict: 'E',
        transclude: true,
        scope: { title:'@' },
        template: '<div style="border: 1px solid black;">' +
                    '<div style="background-color: gray">{{title}}</div>' +
                    '<ng-transclude></ng-transclude>' +
                  '</div>'
      };
  })
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.title = 'Lorem Ipsum';
    $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  }]);
</script>
<div ng-controller="ExampleController">
  <input ng-model="title" aria-label="title"> <br/>
  <textarea ng-model="text" aria-label="text"></textarea> <br/>
  <pane title="{{title}}"><span>{{text}}</span></pane>
</div>

You can also use Multi-slot transclusion, details of which are contained in the link also here

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

4 Comments

Ric, Thanks for your answer. So the HTML inside <pane> will remain as it is? Also, could you please update the link, it seems broken.
Updated the link so it should be ok now. The basics of it is, pane will render the template, and the contents of ng-transclude will be replaced with the dom nodes. you can also have multiple transcludes, which I think is what your'e after
I guess that's what I need. Will give it a try. Thanks a lot.
You can effectively do this: <group><group-title>{{something}}</group-title><group-body>{{something else}}</group-body></group>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.