1

I'm trying to set up a tabbed nav bar that displays content in a div based upon a clicked tab. I'm using ng-repeat in my HTML like so:

HTML:

<ul class ="sidebar-nav">
  <li ng-repeat="category in categories" ng-click="category.method()">{{category.name}}</li>
</ul>

But rather than it calling a method to set it to the active tab when it is clicked, I am seeing that all of the tabs are listed when the page loads and the active tab does not change upon being clicked. Here is my angular:

$scope.setTab = function(activateTab) {
  $scope.tab = activateTab;
  console.log(activateTab);
}; 

$scope.categories = [
  {
  "name" : "Common Tools",
  method : $scope.setTab(1)
  },
...

I tried to set the tab using an anonymous function, as well as using an "id" number inside the individual categories, but I get the same behavior. Any advice?

2
  • Are you saying you tried method: function() { $scope.setTab(1); }? Also, where is $scope.tab being used to determine the active style/class? Commented Nov 19, 2014 at 17:38
  • I did not try it like that but it appears to be setting the tab correctly now. I was hoping to use it in the HTML on a div using ng-show. Is that possible? I'm learning angular and I think that I realized how scope is used through this example a little better, but how would I go about using ng-show now with the active tab? Commented Nov 19, 2014 at 17:42

2 Answers 2

5

Update your code to:

$scope.setTab = function(activateTab) {
  $scope.tab = activateTab;
}; 

$scope.categories =[{"name":"Common Tools"}];

And in your HTML:

<ul class ="sidebar-nav">
  <li ng-repeat="category in categories" 
      ng-click="setTab(category)" 
      ng-class="{active: tab == category}">{{category.name}}</li>
</ul>

Then you can set your styles for the .active class for your tabs.

Sign up to request clarification or add additional context in comments.

Comments

-3

Try this ...

HTML

<ul class ="sidebar-nav">
  <li ng-repeat="category in categories" ng-click="setTab(category.id)" ng-class="{active: category.id === tab}">{{category.name}}</li>
</ul>

JS

$scope.setTab = function (activateTab) {
  $scope.tab = activateTab;
}; 

$scope.categories = [{
  "id": 1,
  "name": "Common Tools"
}];

2 Comments

Was it necessary to post a near identical copy of my answer?
@ClintPowell There is less than 3 minutes between the two.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.