lundi 30 juillet 2018

How to remove undefined checkboxes generated by ng-repeat with modulo operation?

I have the following code (see below), it creates from a given list multiple checkboxes, by using ng-if="$index % 3 == 0", I get 3 columns of checkboxes.

<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></span>
        </div>
        <div class="col-xs-4">
            <input type="checkbox" ng-model="items[$index+1].id">&nbsp;
            <span></span>
        </div>
        <div class="col-xs-4">
            <input type="checkbox" ng-model="items[$index+2].id">&nbsp;
            <span></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

The problem is, that if the number of items in the list is uneven, I get extra checkboxes that are blank/undefined. How can I avoid this?




Aucun commentaire:

Enregistrer un commentaire