Search code examples
cssangularjsng-class

AngularJS - Change multiple CSS classes on 1 <div> from multiple options


I'm afraid I'm new to Angular and therefore my knowledge is limited. I'm hoping there is an easy solution to this and I'd very grateful for any help.

Problem: I have multiple dropdown lists all populated with data from a $scope.list and when one of the lists is clicked, it updates the variables $scope.current. I'm hoping to use the $scope.current array data in a container class elsewhere.

Code:

// ANGULAR

Set the current item
$scope.current = {
    'activeClass1': 'initial-class1',
    'activeClass2': 'initial-class2'
};

Populate the lists
$scope.itemsList1 = [
    {'name': 'foo1'},
    {'name': 'foo2'},
    {'name': 'foo3'}
];

$scope.itemsList2 = [
    {'name': 'bar1'},
    {'name': 'bar2'},
    {'name': 'bar3'}
];

HTML LIST 1

<ul class="dropdown-menu" role="menu">
   <li ng-repeat="item in itemList1">
     <a href="#" ng-click="current.activeClass1=item.name;>{{item.name}}</a>
   </li>
</ul>

HTML LIST 2

<ul class="dropdown-menu" role="menu">
   <li ng-repeat="item in itemList2">
     <a href="#" ng-click="current.activeClass2=item.name;>{{item.name}}</a>
   </li>
</ul>

// HTML TO UPDATE WHEN ABOVE LISTS ARE CLICKED

<div class="container" ng-class="{{current.activeClass1}} {{current.activeClass2}}">
    Note: two classes need to be added to the parent and kept updated 
</div>

// OUTPUT Only initial 'container' class present.

// UPDATE Thanks to the answers given, the jsFiddle showed that it should be working, but my problem was that ng-view was causing problems with my $scope - as soon as separated those dynamic classes and the ng-view, everything worked. Thanks again!


Solution

  • You have two extra closing curly braces in your code. this works: http://jsfiddle.net/s7AK7/

    $scope.current = {
        'activeClass1': 'initialClass',
        'activeClass2': 'initialClass'
    };
    
    $scope.itemsList1 = [
        {'name': 'item1'},
        {'name': 'item2'},
        {'name': 'item3'}
    ];
    
    $scope.itemsList2 = [
        {'name': 'item1'},
        {'name': 'item2'},
        {'name': 'item3'}
    ];