Tuesday 27 January 2015

Using transclude in AngularJS


 

It's actually not possible to define transclude right here now but all I can say is that it is something like appending inner element of custom directive. Here as you can see there is a custom element called button-directive and one span element inside it. And in the script on the directive declaration you can see one addition transclude:true, if this is made to false, span tag will not be included or precisely to say not shown inside the button. If the transclude is set to false button caption will be Where is the mouse, but if it is set to true then 'Lets find it' will be included.



<!DOCTYPE html>
<html data-ng-app="app">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Transclude example</title>
    <link href="style.css" rel="stylesheet" />
    <script src="https://code.angularjs.org/1.0.8/angular.js"></script>
    <script >
       var app = angular.module('app', []);

      app.controller('MainCtrl', function($scope) {
         $scope.name = 'World';
     })
     .directive('buttonDirective',function() {
      return {
      restrict: 'AE',
      transclude:true,
      template:'<button ng-transclude class="btn btn-primary" type="button">' +
      'Where is the mouse</button>'
       }
     })
   </script>
  </head>

  <body data-ng-controller="MainCtrl">
    <button-directive>
      <span class="innertext">Let's find it</span>
    </button-directive>
    <p>Hello {{name}}!</p>
  </body>

</html>

No comments: