2

I need to conditionally add two classes using ng-class.

I want to add class checked if case has commments, and I want to add class lots if the length of the comments array is more than 10.

This works, to add checked if case has comments:

<p class="comments" ng-class="{checked: case.comments}">

But this doesn't work- it doesn't give me checked OR lots:

<p class="comments" ng-class="{checked: case.comments, lots: case.comments.length >= 10}">

Should I skip trying to do this in the HTML & calculate it on a $scope boolean instead, or is there a way to do this in the HTML?

UPDATE: Never mind, the error was in my observational skills, not the code. It works in its given form, but I was looking for the result in the wrong place. D'oh.

Ila
  • 3,528
  • 8
  • 48
  • 76
  • This is a duplicate of http://stackoverflow.com/questions/16529825/angularjs-ngclass-conditional – apohl Jan 24 '14 at 14:49
  • @apohl I think this is a different question. – Dalorzo Jan 24 '14 at 14:53
  • Thats... strange. It is written correctly as far as I can see. Have you tried printing out the length below, just {{case.comments.length}} in the html, just to check that nothing strange is going on when getting .length? – Erik Honn Jan 24 '14 at 15:48

1 Answers1

0

why you don't add a function to to manage this, something like

Here is a plunker sample

controller

$scope.hasComments = function(case){
   var commentsCode = 0;
   if (case.comments){
      commentsCode = 1;
   }
   if (case.comments.length >= 10){
      commentsCode = 2
   }

    return commentsCode ;
}

html

<p class="comments" ng-class="{1: 'checked', 2: 'checked lots'}[hasComments(case)]">
Dalorzo
  • 19,834
  • 7
  • 55
  • 102