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

ng-if搭配ng-repeat与radio按钮使用时未按预期渲染问题

AngularJS 表格id列单选框不按条件显示问题

复现代码

HTML模板

<div ng-app ng-controller="Ctrl">
  <div class="cont">
    <table>
      <tr><th ng-repeat="column in columns">{{column}}</th></tr>
      <tr ng-repeat="(i, row) in people">
        <td ng-repeat="(j, column) in columns">
          <input type="radio" name="select" ng-if="column === 'id'">
          <span>{{row[column]}}</span>
        </td>
      </tr>
    </table>                        
  </div>    
</div>

控制器代码

function Ctrl($scope) {
  $scope.selectedId = 'aaaaa';
  $scope.columns = ['id','name', 'age'];
  $scope.people=[
    { 'id':'aaaaa', 'name':'rachit', 'age':11 },
    { 'id':'bbbbb', 'name':'gulati', 'age':12 },
    { 'id':'ccccc', 'name':'rocks', 'age': 13 }
  ]
}

问题原因

  • 最常见的原因是引入的AngularJS版本过低:ng-if是AngularJS 1.1.5版本才新增的内置指令,如果使用1.0.x及更早的稳定版本,框架无法识别ng-if属性,会直接忽略这个条件控制逻辑,所有写在模板里的radio元素都会被正常渲染,不会被移除。
  • 其次是遍历写法问题:ng-repeat的(key, value)键值对语法是为遍历普通对象设计的,遍历数组时使用这种写法在部分1.x版本中会出现变量映射顺序和预期不一致的问题,导致ng-if里引用的column不是列名字符串,条件判断完全失效。

修复方法

  1. 升级AngularJS到1.2及以上的稳定版本,确保ng-if指令可以被框架正常识别。
  2. 调整ng-repeat遍历数组的写法,不要用对象遍历的键值对语法,改用数组遍历的标准写法,需要索引时直接用框架提供的$index内置变量即可。修改后的单元格代码如下:
<td ng-repeat="column in columns">
  <!-- 可选:补充ng-model和ng-value绑定选中值,让单选框交互功能正常 -->
  <input type="radio" name="select" ng-if="column === 'id'" ng-model="selectedId" ng-value="row.id">
  <span>{{row[column]}}</span>
</td>

修改后只有id列会渲染单选框,其余列的radio元素会被ng-if直接移除,符合预期效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 22:57:09