wonderbell
wonderbell

Reputation: 1126

Replace outer HTML in AngularJS directive

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.

Upvotes: 1

Views: 592

Answers (1)

Ric
Ric

Reputation: 13248

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

Upvotes: 1

Related Questions