0
votes

I just started to try out Angular last day. I'm trying to use bootstrap tabs feature. I want to add class 'active' dynamically to the active li, depending on which tab user clicks. Below is my HTML snippet.

<div ng-controller="TabController as tabs">

{{currentTab}}
<ul class="nav nav-pills" >
  <li ng-class="{'active':tabs.isTab('Events')}" ><a href="#" ng-click="setTab('Events')">Events</a></li>
  <li ng-class="{'active':tabs.isTab('Surveys')}" ><a href="#" ng-click="setTab('Surveys')">Surveys</a></li>
  <li ng-class="{'active':tabs.isTab('Forums')}" ><a href="#" ng-click="setTab('Forums')">Forums</a></li>
</ul>

What I am doing is, when user clicks on any link, I'm caling setTab() method with the tab name and changing the value if 'currentTab'.As you can see, I'm printing the value of 'currentTab' on top of the page, and it is printing as 'Events' first time. And when user clicks on different tabs, I'm able to change the value of currentTab (the value printed on page is changing). But the only thing is, 'active' class is not added to the selected tab. For each li, I check whether currentTab value is matching with specific tab, by calling isTab() method. I have put some logs in the isTab() method, but no logs are getting printed.

Below is my module and controller definition.

var app = angular.module('myApp',[]);

app.controller('TabController',['$scope','$http', function($scope, $http) {

$scope.currentTab = 'Events';

$scope.setTab = function(tabName)  {
    console.log('in setTab '+tabName);      // this is getting called
    $scope.currentTab = tabName;
};

$scope.isTab = function(tabName)  {
    console.log('in isTab '+tabName);                  // this is never printed!
    return $scope.currentTab === tabName;
    //return true;
};  

}]);

1
Why are you using tabs.isTab and not just isTab like you are with setTab? - Ian
try ng-class="(tabs.isTab('Events') ? 'active' : '')" - Gavin Hellyer
something else to consider, I have had issues when declaring a controller TabController as tabs where $scope.isTab had to be this.isTab - Gavin Hellyer
@GavinHellyer.. Thanks for the help...as per your suggestion I changed from tabs.isTab() to isTab() and it worked...I also tried to change $scope.isTab() to this.isTab() and that too worked. What I don't understand is why just defining an alias would need us to change all the definitions inside the controller?> - hashcoder

1 Answers

1
votes

This is because of controller as syntax. If you use this one, you should define all view model data, including funcitons, in this:

this.isTab = function(tabName)  {
    console.log('in isTab '+tabName);
    return this.currentTab === tabName;
};  

It will work.