1

I've got a directive with this markup:

<button type="button" ng-class="{ 'btn-disabled': button.isDisabled }">

As you can see, btn-disabled is added as a CSS class if the scope's button.isDisabled is truthy.

Also on the scope is a property button.glyphicon. If glyphicon is truthy, I'd like to add the value of it to the <button>'s class as well.

How can I do this?

core
  • 32,451
  • 45
  • 138
  • 193
  • 1
    Hem… `{ 'btn-disabled': button.isDisabled, glyphicon: button.glyphicon }`? – Blackhole Aug 01 '14 at 14:07
  • possible duplicate of [Adding multiple class using ng-class](http://stackoverflow.com/questions/18871277/adding-multiple-class-using-ng-class) – William Aug 01 '14 at 14:09
  • 2
    Blackhole: no, the class "glyphicon" will be added, not the value of "glyphicon". – core Aug 01 '14 at 14:15
  • Then, use `ng-class="(button.isDisabled ? 'btn-disabled ' : ' ') + (button.glyphicon || '')"`. And don't hesitate to read [the documentation](http://docs.angularjs.org/api/ng.directive:ngClass). – Blackhole Aug 01 '14 at 14:15

2 Answers2

2

Maybe not the nicest syntax, but you could use:

data-ng-class="[button.isDisabled ? 'btn-disabled' : '', button.glyphicon]"
Yoshi
  • 54,081
  • 14
  • 89
  • 103
1

You could add a function to ng-class.

<button type="button" ng-class="getClass()">...

and on the controller

 $scope.getClass = function(){
       return ($scope.button.isDisabled ? "btn-disabled " : " ") + ($scope.button.glyphicon || "");
   }

By adding this as a function you could reduce one extra watch that will be created while doing it inline in the template and abstract the logic out of html.

PSL
  • 123,204
  • 21
  • 253
  • 243