You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS表格中根据ng-repeat值切换显示不同图标

解决AngularJS根据布尔值切换图标的问题

你之前用的@if是服务器端Razor语法,没法识别AngularJS的客户端变量s.EnableSeriesUpdates,得用Angular的客户端指令来实现条件显示,下面给两种简单可行的方案:

方案一:用ng-class动态切换图标类

这种方式通过条件判断动态添加图标类,代码更简洁:

<tr ng-repeat="s in series">
    @if (isAdmin)
    {
        <td ng-click="actions.remove($index)">
            <span class="glyphicon glyphicon-remove text-danger" title='Delete this series'></span>
        </td>
        <td ng-click="actions.toggle($index)" class="editable-click" style="text-align: center">
            <span 
              class="glyphicon text-warning" 
              ng-class="s.EnableSeriesUpdates ? 'glyphicon-ban-circle' : 'glyphicon-ok-circle'"
              title='Enable/Disable updates for this series'>
            </span>
        </td>
    }
    <td>{{s.ReleaseYear}}</td>
    <td>{{s.TitleId}}</td>
    <td>{{s.TitleName}}</td>
</tr> 
  • 逻辑:当s.EnableSeriesUpdates为true时,显示glyphicon-ban-circle;为false时显示glyphicon-ok-circle(你可以把这个替换成你需要的其他图标类)。

方案二:用ng-if分别渲染两个图标

这种方式把两种状态的图标完全分开,适合需要设置不同样式或提示文字的场景:

<tr ng-repeat="s in series">
    @if (isAdmin)
    {
        <td ng-click="actions.remove($index)">
            <span class="glyphicon glyphicon-remove text-danger" title='Delete this series'></span>
        </td>
        <td ng-click="actions.toggle($index)" class="editable-click" style="text-align: center">
            <!-- 启用状态显示ban图标 -->
            <span 
              class="glyphicon glyphicon-ban-circle text-warning" 
              ng-if="s.EnableSeriesUpdates"
              title='Disable updates for this series'>
            </span>
            <!-- 禁用状态显示ok图标 -->
            <span 
              class="glyphicon glyphicon-ok-circle text-success" 
              ng-if="!s.EnableSeriesUpdates"
              title='Enable updates for this series'>
            </span>
        </td>
    }
    <td>{{s.ReleaseYear}}</td>
    <td>{{s.TitleId}}</td>
    <td>{{s.TitleName}}</td>
</tr> 

额外提醒

要确保你的actions.toggle($index)方法确实在修改EnableSeriesUpdates的值,否则点击后图标不会切换,控制器里的方法大概是这样:

$scope.actions.toggle = function(index) {
    var item = $scope.series[index];
    item.EnableSeriesUpdates = !item.EnableSeriesUpdates;
    // 这里可以添加保存到后端的逻辑
};

内容的提问来源于stack exchange,提问作者linebam59

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 15:43:11