Skip to content

Instantly share code, notes, and snippets.

@umidjons
Created September 25, 2013 11:02

Revisions

  1. umidjons created this gist Sep 25, 2013.
    88 changes: 88 additions & 0 deletions accordion.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,88 @@
    <!doctype html>
    <html lang="en-US" data-ng-app="Accordion">
    <head>
    <meta charset="UTF-8">
    <title>AngularJS: Accordion Example with Custom directives</title>
    <script type="text/javascript" src="js/angular.js"></script>
    <style type="text/css">
    .expander{ border: 1px solid black; width: 250px; }

    .expander>.title{ background: black; color: white; padding: .1em .3em; }

    .expander>.body{ padding: .1em .3em; }
    </style>
    </head>
    <body>

    <div data-ng-controller="SomeController">
    <accordion>
    <expander class="expander" data-ng-repeat="expander in expanders" data-expander-title="{{expander.title}}">
    {{expander.text}}
    </expander>
    </accordion>
    </div>

    <script type="text/javascript">
    angular.module( 'Accordion', [] )
    .directive( 'accordion', function ()
    {
    return {
    restrict : 'EA',
    replace : true,
    transclude: true,
    template : '<div data-ng-transclude=""></div>',
    controller: function ()
    {
    var expanders = [];

    this.gotOpened = function ( selected_expander )
    {
    angular.forEach( expanders, function ( expander )
    {
    if ( selected_expander != expander )
    expander.showMe = false;
    } );
    };

    this.addExpander = function ( expander )
    {
    expanders.push( expander );
    };
    }
    };
    } )
    .directive( 'expander', function ()
    {
    return {
    restrict : 'EA',
    replace : true,
    transclude: true,
    require : '^accordion',
    scope : {title: '@expanderTitle'},
    template : '<div>' +
    '<div class="title" data-ng-click="toggle()">{{title}}</div>' +
    '<div class="body" data-ng-show="showMe" data-ng-transclude=""></div>' +
    '</div>',
    link : function ( scope, element, attrs, accordionController )
    {
    scope.showMe = false;
    accordionController.addExpander( scope );
    scope.toggle = function ()
    {
    scope.showMe = !scope.showMe;
    accordionController.gotOpened( scope );
    };
    }
    }
    } )
    .controller( 'SomeController', function ( $scope )
    {
    $scope.expanders = [
    {title: 'First Expander', text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laudantium, sit.'},
    {title: 'Second Expander', text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo, incidunt.'},
    {title: 'Third Expander', text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestias, nam.'}
    ];
    } );
    </script>
    </body>
    </html>