Angualar 1.x tabs directive
by Krzysztof Safjanowski
HTML
<div ng-app='app'>
<div ng-controller='first'>
<tabs>
<tab title='foo'>
<p>hello {{foo}}</p>
</tab>
<tab title='bar'>
<p>hello bar</p>
</tab>
</tabs>
</div>
<div ng-controller='second'>
<tabs>
<tab title='foo'>
<p>hello {{foo}}</p>
</tab>
<tab title='bar'>
<p>hello bar</p>
</tab>
</tabs>
</div>
</div>
JavaScript
angular.module('app', [])
.controller('first', function($scope) {
$scope.foo = `I'm the first one`
})
.controller('second', function($scope) {
$scope.foo = `I'm the second`
})
.directive('tabs', function() {
return {
restrict: 'E',
transclude: true,
scope: {},
controller: function($scope) {
var tabs = $scope.tabs = []
$scope.select = function(tab) {
angular.forEach(tabs, function(tab) {
tab.selected = false
})
tab.selected = true
}
this.addTab = function(tab) {
if (tabs.length === 0) {
$scope.select(tab)
}
tabs.push(tab)
}
},
template: `
<div>
<ul>
<li ng-repeat='tab in tabs'>
<a ng-href='#' ng-click='select(tab)'>{{tab.title}}</a>
</li>
</ul>
<div ng-transclude></div>
</div>
`
}
})
.directive('tab', function() {
return {
require: '^^tabs',
restrict: 'E',
transclude: true,
scope: {
title: '@'
},
link: function(scope, element, attrs, tabsCtrl) {
tabsCtrl.addTab(scope)
},
template: `
<div ng-show='selected'>
<h4>{{title}}</h4>
<div ng-transclude></div>
</div>
`
}
})