Skip to content

Instantly share code, notes, and snippets.

@kasajian
Created May 21, 2014 16:51
Show Gist options
  • Save kasajian/49706b0757574c6f159e to your computer and use it in GitHub Desktop.
Save kasajian/49706b0757574c6f159e to your computer and use it in GitHub Desktop.
Toggles visibility of child elements.
Convert HTML that looks 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>
to use a collapsable directive 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>

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: '<div><h4 class="well-title" ng-click="toggleVisibility()" ng-bind="title"></h4><div ng-show="visible" ng-transclude></div></div>',
        controller: function($scope) {
            $scope.visible = true;
            $scope.toggleVisibility = function() {
                $scope.visible = !$scope.visible;
            }
        },
        transclude: true,
        scope: {
            title: "@"
        }
    };
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment