ianodork
ianodork

Reputation: 27

Using ng-repeat, ng-click and $scope

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?

Upvotes: 1

Views: 167

Answers (2)

Clint Powell
Clint Powell

Reputation: 2398

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.

Upvotes: 5

dcodesmith
dcodesmith

Reputation: 9614

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"
}];

Upvotes: -3

Related Questions