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
, maxMessageLength
and messageLengthAlertTreshold
are 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-length
nor message-length-alert
are 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?
AngularJS ng-class DirectiveIf it is a string, it should contain one or more, space-separated class names. As an object, it should contain key-value pairs, where the key is the class name of the class you want to add, and the value is a boolean value. The class will only be added if the value is set to true.
Combining NgStyle and NgClass Directives with our knowledge of Angular Template Syntax, we can marry conditional styling with Angular's Property & Event Binding.
Use NgStyle directive to dynamically style multiple CSS properties of an element. ngStyle is applied as an attribute to an element. The square brackets around the directive indicate that the NgStyle directive has an input property also called ngStyle.
Though its late and the actual reason for this problem was mentioned by @tymeJV, in some cases, ngClass , ngStyle and related directives work if the browser tab's cache is cleared. Clear Cache and Hard reload or opening in a new tab will work, if you feel the directive is properly defined.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With