Is there a way to tell which tab that has been selected when using the Bootstrap tabs in Angular UI?
I tried watching the panes array but it deosn't seem to be updated when switching tab. Can one specify a callback function when a tab is selected?
Update with code example.
The code very much follows the example from the Angular UI bootstrap page.
Markup:
<div ng-controller="TabsDemoCtrl">
<tabs>
<pane ng-repeat="pane in panes" heading="{{pane.title}}" active="pane.active">
<div ng-include="pane.template"></div>
</pane>
</tabs>
</div>
Controller:
var TabsCtrl = function ($scope) {
$scope.panes = [
{ title:"Events list", template:"/path/to/template/events" },
{ title:"Calendar", template:"/path/to/template/calendar" }
];
};
Actually this is really simple as each pane exposes the active attribute that supports 2-way data binding:
<tabs>
<pane ng-repeat="pane in panes" heading="{{pane.title}}" active="pane.active">
{{pane.content}}
</pane>
</tabs>
and then an active tab can be easily found, for example:
$scope.active = function() {
return $scope.panes.filter(function(pane){
return pane.active;
})[0];
};
Here is a working plunk: http://plnkr.co/edit/fEvOtL?p=preview
if you don't have a repeater, bind tabs (or spans) activity to an Array
<tab active="tabActivity[0]">...</tab>
<tab active="tabActivity[1]">...</tab>
and in your controller
$scope.tabActivity=[false,false];
then you can get active tab with
$scope.tabActivity.indexOf(true)
I solved it by adding one method (onTabSelect) on the controller and calling it from ng-click event of Tab. Below solution worked for me please see this in action
function myTabController($scope) {
$scope.onTabSelect = function(tabName) {
$scope.selectedTabName = tabName;
console.log("Changed tab to " + tabName);
}
<tabset>
<tab ng-click="onTabSelect('A')">
<tab-heading>
A
</tab-heading>
</tab>
<tab ng-click="onTabSelect('B')">
<tab-heading>
B
</tab-heading>
</tab>
</tabset>
Add an ID to your tabs and then in your controller bind to the a links in the tabs menu with JQuery:
$("#youTabIdHere> ul > li > a").on("click", function(evt){
console.log(evt);
});
note: you will find issues with firing this code after the tabs have initialised. You could always extend/ override the directive or build your own.
Or use John P's solution above to listen for changes to the page data
$scope.active = function() {
if ($scope.panes) {
var i;
for (i=0;i<$scope.panes.length;i++) {
if ($scope.panes[i].active) {
return i;
}
}
}
};
$scope.$watch('active()', function(paneIndex) {
if (paneIndex != undefined) {
var pane = $scope.panes[paneIndex];
$scope.tabHandler(pane); // this would be your function on change
}
});