如何通过模运算删除ng-repeat生成的未定义复选框?

时间:2018-07-30 13:32:07

标签: javascript angularjs checkbox

我有以下代码(见下文),它使用给定的列表创建多个复选框,通过使用ng-if="$index % 3 == 0",我得到3列复选框。

<div ng-controller="TestController" class="container">
    <div ng-repeat="item in items" ng-if="$index % 3 == 0" class="row">
        <div class="col-xs-4">
            <input type="checkbox" ng-model="items[$index].id">&nbsp;
            <span>{{items[$index].name}}</span>
        </div>
        <div class="col-xs-4">
            <input type="checkbox" ng-model="items[$index+1].id">&nbsp;
            <span>{{items[$index+1].name}}</span>
        </div>
        <div class="col-xs-4">
            <input type="checkbox" ng-model="items[$index+2].id">&nbsp;
            <span>{{items[$index+2].name}}</span>
        </div>
    </div>
</div>

var app = angular.module('app', [ ]);
app.controller('TestController', ['$scope', function($scope) {

     $scope.items = [
    {id:0, name:"1/4 Mile"},
    {id:1, name:"1/2 Mile"},
    {id:2, name:"1 Mile"},
    {id:3, name:"2 Mile"},
    {id:4, name:"3 Mile"},
    {id:5, name:"4 Mile"},
    {id:6, name:"5 Mile"}
  ];
}]);

jsfiddle

问题是,如果列表中的项目数为奇数,我会得到额外的空白/未定义的复选框。如何避免这种情况?

1 个答案:

答案 0 :(得分:2)

您可以使用ng-if条件。最后两个空白复选框归因于items[$index+1]items[$index+2]。由于您拥有$index % 3 == 0并不意味着$index+1$index+2存在,因此您可以使用ng-if条件来检查值是否在items数组中。 / p>

var app = angular.module('app', [ ]);
app.controller('TestController', ['$scope', function($scope) {
  $scope.items = [
    {id:0, name:"1/4 Mile"},
    {id:1, name:"1/2 Mile"},
    {id:2, name:"1 Mile"},
    {id:3, name:"2 Mile"},
    {id:4, name:"3 Mile"},
    {id:5, name:"4 Mile"},
    {id:6, name:"5 Mile"}
  ];
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<div ng-app="app" ng-controller="TestController" class="container">
  <div ng-repeat="item in items" ng-if="$index % 3 == 0" class="row">
    <div class="col-xs-4">
      <input type="checkbox" ng-model="items[$index].id">&nbsp;
      <span>{{items[$index].name}}</span>
    </div>
    <div class="col-xs-4">
      <input type="checkbox" ng-if='items[$index+1]' ng-model="items[$index+1].id">&nbsp;
      <span>{{items[$index+1].name}}</span>
    </div>
    <div class="col-xs-4">
      <input type="checkbox" ng-if='items[$index+2]' ng-model="items[$index+2].id">&nbsp;
      <span>{{items[$index+2].name}}</span>
    </div>
  </div>
</div>