Search code examples
angularjsconditional-statementsng-class

AngularJs condition class And regular class


here is the problem, I need to apply a conditional class (add 'card--done' class if completed is true), and, also add the class stored in task.color.

Here's the code:

        <!-- Card -->
        <div class="card" 
            ng-repeat="task in projectsData[currentProject].tasks track by $id(task)"
            ng-class="{'card--done': task.completed}, task.color">
        </div><!-- End of card -->

I tried pretty much everything i could think of, but nothing worked for combining those.

I also tried a function, still won't work.

ng-class="[getClasses(), {'card--done': task.completed}]"

Spent an hour and a half on this, please help :)


Solution

  • You could probably do like this :

    ng-class="[(task.completed && 'card--done') , task.color]"
    

    if task.completed is falsy it will add class name "false" to the element but it should be harmless. Problem is when you provide an array it will use the string representation of every item in the array, so using an object will just show [Object object], unless you evaluate the object with bracket notation like:

     ng-class="[{true: 'card--done'}[task.completed], task.color]"
     //ng-class="[getClasses(), {true: 'card--done'}[task.completed]]"
    

    Plnkr