ngClass Directive: Can I use multiple expressions

2019-07-19 02:48发布

问题:

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.