26

I have a textarea containing a message to be posted and a span with the number of characters still available.

<textarea name="" cols="" rows="" maxLength="{{maxMessageLength}}" ng-model="messageText"/>
<div id="chatmessage-buttons">              
    <a ng-click="sendMessage()"><span>Invia</span></a>
<span ng-class="{message-length-alert: (messageText.length > messageLengthAlertTreshold), message-length: true}">{{maxMessageLength - messageText.length}}</span>
</div>          

messageText, maxMessageLengthand messageLengthAlertTresholdare all defined in the $scope, and the counter inside the span is updated correctly when I insert text in the textarea, changing the value of messageText.length.

However, neither the css class message-lengthnor message-length-alertare ever applied to my span, regardless of the value contained in messageText.

I also tried removing the check for message-length-alert leaving the ng-class attribute with just {message-length: true}, but it's not applied anyway.

What am I missing?

Dor Cohen
  • 16,769
  • 23
  • 93
  • 161
Raibaz
  • 9,280
  • 10
  • 44
  • 65

1 Answers1

69

Try to wrap the class name in quotes. Instead of:

ng-class="{message-length-alert: (messageText.length > messageLengthAlertTreshold), message-length: true}

Try:

ng-class="{'message-length-alert': (messageText.length > messageLengthAlertTreshold), 'message-length': true}

It is because the hash key must be a string or variable-like name.

Jim Simson
  • 2,774
  • 3
  • 22
  • 30
ardentum-c
  • 1,410
  • 13
  • 11
  • 3
    You only need to wrap the class name in quotes if there is a hyphen in the class name. Otherwise you don't need this. – Sprose Oct 26 '16 at 13:39