user3448641
user3448641

Reputation: 31

Having an issue with ng-class during initial load

I have a pretty simple task at hand. Build a list, highlight the active item.

Using ng-class and setting the currently selected item in scope works on a click, but not initially.

What am I overlooking here? Here's the data.

$scope.adminTabs =  [{"name": "Agent"}, 
             {"name": "Agent Queue"},
             {"name": "Skills"}
             ]

and here's the click in the controller along with setting the initial value:

$scope.adminTabs = adminInfo.adminTabs;
  //Default
    $scope.activeAdminTab = $scope.adminTabs[0].name;
    $scope.loadAdminTab = function(){
            $scope.activeAdminTab = this.tab.name;

    }

and finally, the ng-class directive itself in action

<ul>
                    <li data-ng-click="loadAdminTab()"
                        data-ng-repeat="tab in adminTabs"
                        data-ng-model = "admin.selectedTab" 
                        data-ng-class="tab.name == activeAdminTab ? 'selected' : '' ">{{tab.name}}</li>
                </ul>

Problem is, that first item is never set to use the "selected" class, although the scope variable that drives it is indeed set correctly.

Upvotes: 0

Views: 765

Answers (2)

SteamDev
SteamDev

Reputation: 4404

My guess is its an issue w/ scope in the ng-repeat.

Try changing:

$scope.activeAdminTab = $scope.adminTabs[0].name;

and

data-ng-class="tab.name == activeAdminTab..."

To:

$scope.obj = {};
$scope.obj.activeAdminTab = $scope.adminTabs[0].name;

and

data-ng-class="tab.name == obj.activeAdminTab..."

Haven't tested, but this is a common issue I encounter w/ angular ng-repeat scopes; solution might work for you.

Upvotes: 0

Gruff Bunny
Gruff Bunny

Reputation: 27976

This isn't an answer so please don't accept it or vote it up. Only here because I created a code snippet showing the code working:

angular.module('MyModule', [])

.controller('MyController', function($scope) {

  $scope.adminTabs =  [{"name": "Agent"}, 
    {"name": "Agent Queue"},
    {"name": "Skills"}
    ];
  
  $scope.activeAdminTab = $scope.adminTabs[0].name;
  
  $scope.loadAdminTab = function(){
     $scope.activeAdminTab = this.tab.name;
  }
});
.selected {
  color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='MyModule' ng-controller='MyController'>
  <ul>
    <li data-ng-click="loadAdminTab()"
        data-ng-repeat="tab in adminTabs"
        data-ng-model = "admin.selectedTab" 
        data-ng-class="tab.name == activeAdminTab ? 'selected' : '' ">{{tab.name}}</li>
  </ul>
</div>

Upvotes: 1

Related Questions