Search code examples
angularjstwitter-bootstrap-3ng-class

Having ng-class in angularjs replace instead of append to CSS classes?


I am doing an SPA to test out my AngularJS knowledge. In this app, I have a template where-by users can choose buttons to show how many days of weather forecast they want.

I am using Twitter Bootstrap classes with the AngularJS ngClass to dynamically have the Twitter Bootstrap CSS classes bound to the button elements depending on which button is selected.

What I wish to happen is, with using ng-class in the HTML of the template, if the button is chosen, it will then change the Bootstrap CSS class of that button to btn btn-disabled from btn btn-primary, so it cannot be selected, as it all ready is selected. I did this in the HTML for this template as so —

  <div class="btn-group" role="group">
    <a href="#/forecast/1" class="btn btn-primary" ng-class="{  'btn btn-disabled' : days === '1' }">1 Day Forecast</a><a href="#/forecast/2" class="btn btn-primary" ng-class="{  'btn btn-disabled' : days === '2' }">2 Day Forecast</a><a href="#/forecast/3" class="btn btn-primary" ng-class="{  'btn btn-disabled' : days === '3' }">3 Day Forecast</a>
  </div>
  <div class="btn-group" role="group">
    <a href="#/forecast/5" class="btn btn-primary" ng-class="{  'btn btn-disabled' : days === '5' }">5 Day Forecast</a><a href="#/forecast/7" class="btn btn-primary" ng-class="{  'btn btn-disabled' : days === '7' }">7 Day Forecast</a><a href="#/forecast/10" class="btn btn-primary" ng-class="{  'btn btn-disabled' : days === '10' }">10 Day Forecast</a>
  </div>

However, when I run this, instead of replacing the Bootstrap CSS class for the element btn btn-primary and change it to btn btn-disabled, as desired; instead, it appends onto the element, so it becomes btn btn-primary btn-disabled all as one, and btn-primary overrules everything visually, so it winds up looking like this in the output —

<a href="#/forecast/1" class="btn btn-primary btn-disabled" ng-class="{  'btn btn-disabled' : days === '1' }">1 Day Forecast</a>

Naturally, this is not the desired effect I want here. Would someone please tell me how, in AngularJS ngClass, do i have it replace the Bootstrap CSS class, not just append it?


Solution

  • You are correct, using ng-class will add the classes when evaluated as true. So the solution is to add both options to ng-class so that either btn-primary or btn-disabled is added at any time.

    <a href="#/forecast/1" class="btn" 
        ng-class="{'btn-disabled': days === '1', 'btn-primary': days !== '1'}">1 Day Forecast</a>
    

    You also don't need to add the class btn to the ng-class since you want it to be used regardless of the value of days.