简体   繁体   English

ngClass 不工作?

[英]ngClass not working?

I am new to AngularJS and I understand that the ngClass directive can be used to insert classes dynamically into elements like:我是 AngularJS 的新手,我知道 ngClass 指令可用于将类动态插入到元素中,例如:

<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. angular 会自动评估哪些条件为真,并将这些特定的类插入到元素中。

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?是语法问题吗?

你的类名中有一个破折号,所以使用单引号!

ng-class="{'has-success': form.email.$valid}"

It is clearly a parser error, you have invalid syntax due to the presence of - in the property name @ {has-success: form.email.$valid} .这显然是一个解析器错误,由于-在属性名称 @ {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}">

If you use '-' in the class name you should cover the class name using single quotes.如果在类名中使用“-”,则应使用单引号将类名括起来。

[ngClass] = "{'some-class': condition}"

otherwise can be use否则可以使用

[ngClass] = "{someClass : condition}"

这对我有用

[ngClass] = "{ 'color-red': isRed}"

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.尽管@tymeJV 提到了这个问题的后期和实际原因,但在某些情况下,如果清除浏览器选项卡的缓存, ngClassngStyle和相关指令会起作用。 Clear Cache and Hard reload or opening in a new tab will work, if you feel the directive is properly defined.如果您认为指令定义正确,则Clear Cache and Hard reload或在新选项卡中打开将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM