Angular Accordian

by JQ Purfect

HTML

<script src="http://code.angularjs.org/1.2.5/angular.js"></script>
<div ng-app>
    <div class="accordion__container" ng-controller="myCtrl">
        <div class="accordion__tab">
            <div class="accordion__tab--title" ng-click="openTab('tab one')">Tab 1</div>
            <div class="accordion__tab--content" ng-show="isOpenTab('tab one')">Tab content goes here!</div>
        </div>
        <!-- .accordion__tab -->
        <div class="accordion__tab">
            <div class="accordion__tab--title" ng-click="openTab('tab two')">Tab 2</div>
            <div class="accordion__tab--content" ng-show="isOpenTab('tab two')">Tab content goes here!</div>
        </div>
        <!-- .accordion__tab -->
        <div class="accordion__tab">
            <div class="accordion__tab--title" ng-click="openTab('tab three')">Tab 3</div>
            <div class="accordion__tab--content" ng-show="isOpenTab('tab three')">Tab content goes here!</div>
        </div>
        <!-- .accordion__tab -->
    </div>
</div>

CSS

.accordion__container {
    background: #eee;
    border: 1px solid #ccc;
    padding: 20px;
}
.accordion__tab {
    background: #aaa;
    color: #fff;
    border-bottom: 1px solid white;
}
.accordion__tab--title {
    background: #888;
    padding: 5px;
    cursor: pointer;
}
.accordion__tab--content {
    background: #999;
    padding: 20px;
}

JavaScript

function myCtrl($scope) {
    //initiate an array to hold all active tabs
    $scope.activeTabs = [];

    //check if the tab is active
    $scope.isOpenTab = function (tab) {
        //check if this tab is already in the activeTabs array
        if ($scope.activeTabs.indexOf(tab) > -1) {
            //if so, return true
            return true;
        } else {
            //if not, return false
            return false;
        }
    }
    
    //function to 'open' a tab
    $scope.openTab = function (tab) {
        //check if tab is already open
        if ($scope.isOpenTab(tab)) {
            //if it is, remove it from the activeTabs array
            $scope.activeTabs.splice($scope.activeTabs.indexOf(tab), 1);
        } else {
            //if it's not, add it!
            $scope.activeTabs.push(tab);
        }
    }
}