简体   繁体   English

如何在Angular.js的ng-class中使用包含破折号的类?

[英]How can I use a class containing dashes in ng-class of Angular.js?

In my Web App, I'm using ng-class="{highlighted_category: selected === category}" to highlight an entry when it is selected. 在我的Web应用程序中,我使用ng-class="{highlighted_category: selected === category}"来突出显示选中的条目。 Problems occur when I want to use eg pure-menu-selected because it contains dashes which Angular does not allow for some reason. 当我想使用例如pure-menu-selected时出现问题,因为它包含Angular由于某种原因不允许的破折号。

Error: [$parse:syntax] Syntax Error: Token '-' is unexpected, expecting [:] at column 6 of the expression [{pure-menu-selected: selected === category}] starting at [-menu-selected: selected === category}].

What would be an elegant way to solve this? 解决这个问题的优雅方法是什么? Why does Angular not allow dashes in ngClass? 为什么Angular不允许在ngClass中使用破折号?

Use single quotes to quote the class name 使用单引号引用类名

ng-class="{'pure-menu-selected': selected === category}"

The reason you can't use dashes unquoted is simple and makes sense. 你不能使用破折号的原因很简单,也很有道理。 It's essentially the key of an object. 它本质上是一个对象的关键。 It's the same reason a variable name cannot contain dashes. 这与变量名称不能包含破折号的原因相同。

Say you tried to have a variable name ab . 假设您尝试使用变量名称ab Does that mean a variable named ab or does it mean a minus b ? 这是指一个名为ab的变量还是a减去b的变量?

Angular is treating your class as variable and you cannot use dash in variable names. Angular将您的类视为变量,您不能在变量名中使用dash。 You can return class as string via function in example: 您可以通过示例中的函数将类作为字符串返回:

ng-class="{getHighlightedClass() : selected === category}". ng-class =“{getHighlightedClass():selected === category}”。

Where getHighlightedClass() you mus to implement in your controller. getHighlightedClass()你可以在你的控制器中实现。

By the way you can bind class directly as string. 顺便说一句,您可以直接将类绑定为字符串。 In example: 例如:

ng-class="{'pure-menu-selected' : selected === category}". ng-class =“{'pure-menu-selected':selected === category}”。

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

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