ngClass Directive: Can I use multiple expressions to add multiple classes?

主宰稳场 提交于 2019-12-14 02:15:41

问题


Here is an example of what I want to achieve

data-ng-class="{ 'tooltip_show' : showTooltip , 'tooltip__' + brand.settings.name }" 

but it doesn't work.


回答1:


Use the array form for ng-class:

<div ng-class="[showTooltip ? 'tooltip_show' : '',
                'tooltip__' + brand.settings.name]">
<div>

OR compute the class in JavaScript:

<div ng-class="computeClass(tooltip_show, brand.setting.name)">
</div>
$scope.computeClass(show, name) {
    var obj = {};
    obj.showTooltip = show;
    obj['tooltip_'+name] = true;
    return obj;
};

The later approach is more easily debugged and better for complex computation.

See also,

  • AngularJS ng-class Directive Reference - Known Issues
  • AngularJS Developer Guide - Why mixing interpolation and expressions is bad practice



回答2:


It looks like you haven't set a value for the second item. Did you mean something like

{ 'tooltip_show' : showTooltip , 'tooltip__' + brand.settings.name : tooltipText }

or

{ 'tooltip_show' : showTooltip , 'tooltip__' : brand.settings.name }

?




回答3:


http://jsbin.com/genaqapefe/edit?html,js,output

data-ng-class="{ 'tooltip_show': showToolTip, {{ 'tooltip_' + brand.settings.name }}: true }"

This is working for me in this bin. I couldn't get it to evaluate without the curly braces, although not sure if that's the best practice.



来源:https://stackoverflow.com/questions/45104001/ngclass-directive-can-i-use-multiple-expressions-to-add-multiple-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!