0

I am using a directive and want to use ng-class in a way that I could output multiple classes (which are stored in a variable) under certain condition.

<div ng-if="showIcons" ng-class="{state.icon: showIcons}"></div>
$scope.state = { 
    icon: 'icon-cross-outline color-brand-danger'
};

Unfortunately this is not working.

2
  • Which version of Angular are you using? Commented Feb 21, 2017 at 15:30
  • Angular ver 1.5.5 Commented Feb 21, 2017 at 15:35

2 Answers 2

2

Using ternary operator in ng-class, could you try the following?

<div ng-if="showIcons" ng-class="showIcons ? state.icon : null"></div>

Demo on Plunker

Sign up to request clarification or add additional context in comments.

4 Comments

@be-codified On this Plunker, it works for me.
Thank you for your effort. Perhaps my problem lies somewhere else.
@be-codified Yes, I think. Try to hard-code your classes. Does it works? Is state.icon a String? Are you sure your classes exists in CSS? Play with my Plunker, maybe you will fix your issue from it. :-)
It works if I try to hardcode, so it must be something with value of state.icon :) Will do.
0

You can do more complicated stuff via binding a function to the ng-class see my plnker

JS:

var app = angular.module('hey', []);

app.controller('TheController', [function () {
  this.title = "hey"
  this.shouldApply = true;

  this.canApplyClass = function () {
    if (this.shouldApply == true) {
      return 'happy sad other';
    }

    return '';
  }
}]);

HTML:

<body ng-app="hey">
  <div ng-controller="TheController as c">
    <h1 ng-class="c.canApplyClass()">{{c.title}}</h1>  
  </div>
</body>

I prefer this approach because you can get complicated in the function - and even have access to other services.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.