Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngClass not working?

Tags:

I am new to AngularJS and I understand that the ngClass directive can be used to insert classes dynamically into elements like:

<input ng-class="{some-class: condition, another-class: anotherCondition}"> 

And angular will automatically evaluate which conditions are true and will insert those particular classes in the element.

Now I am trying to do something like:

<div class="form-group" ng-class="{has-success: form.email.$valid}"> 

Since I have bootstrap, it will automatically color the label and the input green if the email is valid. But it doesn't work and I am getting this particular error in the console:

Error: [$parse:syntax] http://errors.angularjs.org/1.2.27/$parse/syntax?p0=-&p1=is%20unexpected%2C%20expecting%20%5B%3A%5D&p2=5&p3=%7Bhas-success%3A%20form.email.%24valid%7D&p4=-success%3A%20form.email.%24valid%7D z/<@http://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:6:450 

and so on....

What am I doing wrong? Is it a syntax issue?

like image 505
Rohan Avatar asked Jan 15 '15 17:01

Rohan


People also ask

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.

How do I apply NgClass condition?

To add a conditional class in Angular we can pass an object to ngClass where key is the class name and value is condition i.e., true or false as shown below. And in the above code, class name will be added only when the condition is true.

What is the use of NgClass in Angular 8?

ngClass is a directive in Angular that adds and removes CSS classes on an HTML element.


2 Answers

Theres a dash in your class name, so use single quotes!

ng-class="{'has-success': form.email.$valid}" 
like image 160
tymeJV Avatar answered Sep 16 '22 18:09

tymeJV


It is clearly a parser error, you have invalid syntax due to the presence of - in the property name @ {has-success: form.email.$valid}. You would need to wrap them in quotes.

Try:-

<div class="form-group" ng-class="{'has-success': form.email.$valid}"> 
like image 27
PSL Avatar answered Sep 20 '22 18:09

PSL