Javascript ngClass 不工作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27969218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:01:50  来源:igfitidea点击:

ngClass not working?

javascriptangularjstwitter-bootstrap

提问by Rohan

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?

我究竟做错了什么?是语法问题吗?

回答by tymeJV

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

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

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

回答by PSL

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.

这显然是一个解析器错误,由于-属性名称 @ 中的存在,您的语法无效{has-success: form.email.$valid}。您需要将它们用引号括起来。

Try:-

尝试:-

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

回答by Sashini Hettiarachchi

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}"

回答by Zohab Ali

This worked for me

这对我有用

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