Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-class not being applied

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?

like image 813
Raibaz Avatar asked Mar 28 '13 11:03

Raibaz


People also ask

How to use Ng class in AngularJS?

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.

Can we use ngClass and NgStyle together?

Combining NgStyle and NgClass Directives with our knowledge of Angular Template Syntax, we can marry conditional styling with Angular's Property & Event Binding.

When to use NgStyle?

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.

Why my ngClass is not working?

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.


1 Answers

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.

like image 111
ardentum-c Avatar answered Sep 22 '22 16:09

ardentum-c