ng-class if else 不使用重复值

ng-class if else not working with repeat value

我一直在尝试更改 class 如果标签重复,具体取决于标签的标题。下面显示的片段

 <tab ng-repeat="tab in tabs" heading="{{tab.title}}" ng-class="{{tab.title}} === 'Logs' ? 'pull-right' : ''" active="tab.active">
            <div class="col-md-12">
                <div ng-include="tab.content">
                </div>
            </div>
        </tab>

但它不起作用。我尝试将 tab.title 更改为 $index.

<tab ng-repeat="tab in tabs" heading="{{tab.title}}" active="tab.active" ng-class="{{$index}} === 1 ? 'pull-right' : ''">
            <div class="col-md-12">
                <div ng-include="tab.content">
                </div>
            </div>
        </tab>

尝试用 {} 和 {{}} 围绕它。但仍然。没有任何效果。

谁能告诉我我做错了什么?

一如既往,感谢您的宝贵时间。

----编辑--------

好吧,我找到了一个 post 解决方法。不知道会发生什么。但它有效。 下面显示的片段

              <tab ng-repeat="tab in tabs" heading="{{tab.title}}" active="tab.active" class="{{ tab.title == 'Logs' ? 'pull-right':'' }} ">
            <div class=" col-md-12">
            <div ng-include="tab.content">
            </div>

您应该为 ng-class 使用此语法。首先是要设置的 class 名称,其次是要检查的条件。一旦符合条件,将添加 class 名称。

<tab ng-repeat="tab in tabs" heading="{{tab.title}}" ng-class="{ 'pull-right': tab.title == 'Logs' }" active="tab.active">
    <div class="col-md-12">
        <div ng-include="tab.content">
        </div>
    </div>
</tab>

the docs所述,ng-class的值是一个表达式,可以计算为字符串、对象或数组。这意味着您不必在那里使用 {{}}:简单...

ng-class="tab.title === 'Logs' ? 'pull-right' : ''"

...应该足够了。其实写成对象更干净:

ng-class="{'pull-right':tab.title === 'Logs'}"

遗憾的是,这无法解决您的问题,因为您正在尝试将 ng-class 应用于自定义指令(使用 angular-ui Bootstrap 创建包裹)。该指令在 its own template:

中使用 ng-class
<li ng-class="{active: active, disabled: disabled}">
  <a href ng-click="select()" tab-heading-transclude>{{heading}}</a>
</li>

... 它是在 replace 标志设置为 true 的情况下创建的。这实际上意味着您提供的 ng-class 的值将与模板提供的值粘合在一起,导致一些丑陋的东西,例如:

<li ng-class="tab.title === 'Logs' ? 'pull-right' : '' {active: active, disabled: disabled}">

这肯定不会按计划进行。事实上,在项目中心注册了一个相关问题 (#1741) - 已关闭并附有以下评论:

Using ng-class on a directive that uses replace: true is a very bad idea. There are numerous issues around replace: true and even talk of deprecating/removing it. But, unfortunately, it's not going anywhere soon and the caveat released by the core Angular team was that use it, but do so at your peril. I.e., use it knowing that doing so incorrectly can break your DOM.

I suspect this issue will not be addressed.

一种可能的解决方法是使用本机 class 并提供一个 Angular 表达式作为其值:

class="{{tab.title === 'Logs' ? 'pull-right' : ''}}"

这不会与 <tab> 模板 class 合并,因为那里没有这样的东西 - 你可以继续了!