2

I was wondering if there were no compatibility issues when ng-switch-when and ng-class are using on the same element like in this sample.

I'm trying to dynamically change the class of this four elements but for some reasons this isn't working on all of them, just on the one who's currently displayed.

Does anyone know what's going on here?

<div>
    <div ng-switch="sw" ng-init="sw=1">
        <div ng-switch-when="1" ng-class="oneClassOrAnother()"></div>
        <div ng-switch-when="2" ng-class="oneClassOrAnother()"></div>
        <div ng-switch-when="3" ng-class="oneClassOrAnother()"></div>
        <div ng-switch-when="4" ng-class="oneClassOrAnother()"></div>
    </div>
    <div>
        <button ng-click="goTo(1)">1</button>
        <button ng-click="goTo(2)">2</button>
        <button ng-click="goTo(3)">3</button>
        <button ng-click="goTo(4)">4</button>
    </div>
</div>

Switch between divs.

$scope.goTo = function(x) {
    $scope.sw = x;
}

Return one class or the other one.

$scope.oneClassOrAnother= function() {
    if (...) return "class1";
    else return "class2";
}

Many thanks.

Brain Up
  • 163
  • 2
  • 10

2 Answers2

1

It doesn't look like you're using the ng-class syntax correctly. Try something like this:

<div ng-class="{class1: oneClassOrAnother()}" ng-switch-when="1">1</div>

Where oneClassOrAnother() returns either true or false and "class1" is the name of the class.

Here's a working example of using ng-class and ng-switch-when together: http://plnkr.co/edit/n86SKEktRcPnBy05o8eZ?p=preview

Angular ngClass docs: https://docs.angularjs.org/api/ng/directive/ngClass

patorjk
  • 2,164
  • 1
  • 20
  • 30
1

I think its all fine with your code, look at this plunk, I reproduced it and its working. Compare this to your code, maybe you have forgotten about controller?

http://plnkr.co/edit/Lz7L3S?p=preview

Only difference i guess is the fact, that I initiated sw from controller, not from view.

<div ng-switch on="sw">

Marcus
  • 341
  • 1
  • 8
  • Ok, that's working. My problem should come from the rest of my code (that was just a sample for better understanding). But actually when I was debugging I try to add a console.log() to oneClassOrAnother(). I wanted to try if it was really launched from each ng-class and surprisingly it seems to log strange things, twice the log of the one which have been clicked. Check it on the plunker, more clearer : [link](http://plnkr.co/edit/wy9RPqvGMHr3QD6U7lje?p=preview) Shouldn't it have logged this instead on each click ? **I am One I am Two I am Three I am Four** It's probably a DOM issue no ? – Brain Up Jul 22 '15 at 11:25