Monday, June 16, 2014

Angular Directives Part 6 - Angular directive with transclude



Convert HTML that looks like this:

    <collapsible title="Star Wars">
        <h6>Show times:</h6>
        <p>12 PM, 3 PM, 6:15 PM, 8:45 PM</p>
        <h6>Theaters:</h6>
        <p>Sherman Oaks Galleria, La Reina Theater</p>
    </collapsible>

to use a collapsable directive like this:

    <h4>Star Wars</h4>
    <h6>Show times:</h6>
    <p>12 PM, 3 PM, 6:15 PM, 8:45 PM</p>
    <h6>Theaters:</h6>
    <p>Sherman Oaks Galleria, La Reina Theater</p>

JavaScript:

// Use transclusion, without it, the replace=true will replace all child elements, too.
// by transclude=true will replace the element with the ng-transclude attribute with the child elements.
angular.module('app').directive('collapsible', [function () {
    return {
        restrict: 'E',
        replace: true,
        template: '

', controller: function($scope) { $scope.visible = true; $scope.toggleVisibility = function() { $scope.visible = !$scope.visible; } }, transclude: true, scope: { title: "@" } }; }]);

No comments: