Thursday, 25 June 2015

angularjs directive transclude.

Transclude can make directives' "contents" to display.

For example:  if you make Lala directive for a image:

<Lala></Lala>

Above code will display a image for you.


If you do:   <Lala><h1>aaaaa</h1></Lala>

It will still display the image but without "aaaaaa".

If you want to display "<h1>aaaaa</h1>" you need transclusion!!!!




<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}}">{{text}}</pane>
</div>

can control the place of displaying contents  <ng-transclude>

it will give parent scope to contents.






if you want to manually do it:


.directive("xxx", function(){
    return {
        scope:true,
        transclude:true,

       link: function (scope, el, attrs, controller, transclusion){
           transclusion(scope, function (content){
             el.append(content);
          })
       }
   };
});




About scope:










No comments:

Post a comment