Created
October 24, 2017 09:06
-
-
Save vesparny/88d40301550767a388236edc0838401b to your computer and use it in GitHub Desktop.
angular 1 tab component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function (angular, document, window, undefined) { | |
'use strict'; | |
angular.module('tabs', []) | |
.directive('kTabs', function () { | |
return { | |
restrict: 'E', | |
scope: { | |
alignment: '@' | |
}, | |
controller: ['$scope', function ($scope) { | |
var panes = $scope.panes = []; | |
var _this = this; | |
this.selectPane = function (pane) { | |
angular.forEach(panes, function (pane) { | |
pane.selected = false; | |
}); | |
pane.selected = true; | |
}; | |
this.addPane = function (pane) { | |
if (panes.length === 0) { | |
$scope.select(pane); | |
} | |
panes.push(pane); | |
}; | |
this.removePane = function (pane) { | |
var paneIndex = panes.indexOf(pane); | |
// if pane was selected then select previous pane | |
if (pane.selected && panes.length > 1) { | |
var toSelectIndex = (paneIndex > 0) ? paneIndex - 1 : 1; | |
panes[toSelectIndex].selected = true; | |
} | |
panes.splice(paneIndex); | |
}; | |
$scope.select = function (pane) { | |
_this.selectPane(pane); | |
}; | |
}], | |
link: function (scope) { | |
scope.alignment = scope.alignment || 'center'; | |
}, | |
template: [ | |
'<div>', | |
'<ul class="Tabs u-cf Tabs--align{{alignment}}">', | |
'<li ng-repeat="pane in panes" ng-class="{active:pane.selected}" class="Tab-li">', | |
'<a href="" class="Tab-anchor"ng-click="select(pane)">{{pane.heading}}</a>' , | |
'</li>', | |
'</ul>', | |
'<div class="Tabs-tabContent" ng-transclude></div>', | |
'</div>'].join(''), | |
replace: true, | |
transclude: true | |
}; | |
}). | |
directive('kPane', function () { | |
return { | |
require: '^kTabs', | |
restrict: 'E', | |
scope: { | |
heading: '@', | |
initForceSelect: '@', | |
hasForceSelect: '@', | |
forceSelect: '=' | |
}, | |
link: function (scope, element, attrs, tabsCtrl) { | |
tabsCtrl.addPane(scope); | |
if (scope.initForceSelect) { | |
tabsCtrl.selectPane(scope); | |
} | |
if (scope.hasForceSelect) { | |
scope.$watch(function () { return scope.forceSelect;}, function (newVal) { | |
if (newVal) tabsCtrl.selectPane(scope); | |
}); | |
} | |
scope.$on('$destroy', function () { | |
tabsCtrl.removePane(scope); | |
}); | |
}, | |
template: '<div class="Tabs-pane" ng-class="{active: selected}" ng-transclude></div>', | |
transclude: true, | |
replace: true | |
}; | |
}); | |
})(angular, document, window); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment