Skip to content

Instantly share code, notes, and snippets.

@andykant
Last active December 21, 2015 04:48
Show Gist options
  • Save andykant/6251703 to your computer and use it in GitHub Desktop.
Save andykant/6251703 to your computer and use it in GitHub Desktop.
Tabs component in Angular
<!doctype html>
<html ng-app="App">
<head>
<script src="http://code.angularjs.org/1.2.0rc1/angular.js"></script>
<script src="tabs.js"></script>
<script src="script.js"></script>
<link rel="stylesheet" href="tabs.css" />
</head>
<body>
<div ng-controller="Ctrl1">
<tabs>
<panel title="breads" id="breads">english muffin, whole wheat toast</panel>
<panel title="veggies">carrot, lettuce</panel>
<panel title="fruit" id="fruit">apple, pears</panel>
</tabs>
</div>
</body>
</html>
function Ctrl1($scope) {
$scope.panels = [
"Panel 1",
"Panel 2",
"Panel 3"
]
}
angular.module("App", ["tabs"]);
tabs .tabs {
list-style: none;
}
tabs .tabs li {
background: #fdfdfd;
border: 1px solid #eee;
cursor: pointer;
display: inline-block;
padding: 4px 2px;
}
tabs .tabs li.active {
background: #eee;
font-weight: bold;
}
tabs .content li {
border: 1px solid #eee;
display: none;
padding: 4px;
width: 400px;
}
tabs .content li.active {
display: block;
}
angular.module("tabs", [])
.directive("tabs", function() {
return {
restrict: 'E',
replace: false,
transclude: true,
template: '<ul class="tabs" ng-transclude></ul>' +
'<ul class="content" ng-transclude></ul>',
link: function(scope, lElem, lAttrs) {
scope.$watch('data', function() {
var panels = lElem.children().eq(0).find('li');
for (var i = 0; i < panels.length; i++) {
!function(i) {
// Replace the tabs with their titles.
panels.eq(i).html(panels.eq(i).scope().title);
// Add click events
panels.eq(i).on('click', function() {
lElem.find('li').removeClass('active');
lElem.children().eq(0).find('li').eq(i).addClass('active');
lElem.children().eq(1).find('li').eq(i).addClass('active');
})
}(i);
}
// Add initial active tabs
panels.eq(0).addClass('active');
lElem.children().eq(1).find('li').eq(0).addClass('active');
});
}
};
})
.directive("panel", function() {
return {
restrict: 'E',
replace: true,
transclude: true,
template: '<li class="tabs-panel" title="{{title}}" id="{{id}}" ng-transclude></li>',
scope: {
title: "@title",
id: "@id"
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment