What is the best approach to eliminating unchecked checkboxes produced by ng-repeat when using modulo operation?

In the code snippet below, I am generating multiple checkboxes from a list and arranging them into three columns using ng-if="$index % 3 == 0".

<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"}
  ];
}]);

View the example on jsfiddle

An issue arises when the number of items in the list is odd, resulting in extra undefined checkboxes. How can this be resolved?

Answer №1

To handle the issue of the last two checkboxes being blank, you can implement an ng-if condition. It's important to note that just because $index % 3 == 0 doesn't mean that $index+1 and $index+2 will always exist in the array. By using the ng-if condition, you can ensure that the values at those indexes actually exist in the items array before rendering them.

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with PDF File Name Not Being Considered in Internet Explorer 10 and Edge

When using the following code, I have noticed that the name of the PDF file is incorrect, appearing as a string of random letters similar to a UUID. This issue seems to only occur in Internet Explorer 10 / Edge. The version of AngularJS being used is 1.4 ...

Mastering the use of Action.Submit in adaptive cards to simulate user input

I am trying to implement MessageFactory.SuggestedActions within my "welcomeCard" adaptive card. Essentially, in my adaptive card (welcome card), I have several buttons for the user to click on, each with an Action.Submit type. { "type" ...

JavaScript prototype error: caught TypeError - attempting to call undefined function

I am facing challenges while attempting to create a Factory in AngularJS. I have moved the code from the controller to the factory and made a few adjustments for it to function properly. Here is the error that I am encountering: "El objeto no acepta la p ...

Seems like the ng-show events inside are not being triggered, almost like an invisible image

I am encountering an issue where no JavaScript events are triggering inside an ng-show div in my code. You can access my code through the following link on Plnkr: http://plnkr.co/edit/kGqk8x?p=preview Upon loading data from JSON, I set ng-show to true. Ho ...

Tips for setting the background image of the body once the image has finished loading

On my website, I have decided to incorporate high-resolution images as the background for the body. However, when I use document.body.style.backgroundImage = "url('URL OF PICTURE')";, the image loads vertically down the page which is not ideal. I ...

A step-by-step guide on generating a single chip using the same word in Angular

I'm trying to find a solution to ensure that only one chip is created from the same word inputted, instead of generating duplicates. Currently, users can input variations such as "apple," "APPLE," "apPPle," "aPpLe," and I want to automatically conver ...

Check each field in a loop and if validation for any field fails, then return false using jQuery

Having trouble resetting the flag variables when it comes to form validations. I seem to be missing something crucial. I'm dealing with a form that has multiple text fields. I want to validate each field on blur and prevent form submission if any val ...

Using the _id String in a GraphQL query to retrieve information based on the Object ID stored in a

Encountering an issue with my graphql query not returning anything when sending the _id as a string. Interestingly, querying the DB using any other stored key (like name: "Account 1") works perfectly and returns the object. I've defined my Account sch ...

Ways to convert JavaScript object to hashmap

I am attempting to generate a map of type <String, Array()> from a JSON object. Suppose I have the following JSON structure: [ { "userId": "123123", "password": "fafafa", "age": "21" }, { "userId": "321321 ...

What is the best way to store a jQuery AJAX response in a PHP variable?

How can I pass a jQuery ajax response into a PHP variable after success in my code: process.php $start = ""; $end = ""; if(isset($_POST['tampStart'])) { $start = $_POST['tampStart']; } if(isset($_POST[& ...

Create a customizable JavaScript clock that synchronizes with an image to display the current hour, minute

I am having trouble with my clock not working I have created images for the hour, minute, second, and AM/PM https://i.sstatic.net/4zg00.png I attempted to use this code: <script language="JavaScript1.1"> <!-- /* Live image clock III Written b ...

Stop the background from scrolling and prevent auto-jumping to the top on mobile devices

When users click on the hamburger icon in the top right of our mobile site, I want the drop-down menu to appear and be scrollable without the background scrolling. I tried using JavaScript to set the body to fixed when the menu icon is clicked, but this ca ...

The model.find operation is failing to retrieve the necessary fields from the database

When I execute console.log(correct.password), it returns undefined, even though the if condition results in false. app.post('/login' , async (req , res)=> { const correct = data.findOne({name : req.body.name}).select({name : 0}); if(!c ...

sending XML data through Google Maps API V3

While working on integrating the google maps api v3, I encountered an issue when trying to pass an XML file to populate the map with results. Upon checking the PHP file responsible for generating the XML data, everything seems to be in order. The PHP file ...

Is AJAX the best way to resize a div on button click?

I am seeking to dynamically change the size of a div element on the client-side. By default, its height is set to 500px, but I want it to increase to 700px when a button is clicked. This task involves an ASP.NET website. I have been instructed to accompl ...

Manipulating HTML content with jQuery

Review the code snippet provided below <div id="post-1234"> <h3><a href="some link">text</a></h3> <div> <div> <div> <span class"Event-Date">Event Date 1</span> </div> < ...

Utilize the power of checkboxes in Vue.js and Quasar framework to enable specific functionalities upon being

There are two checkboxes available: 'Show Active' and 'Show Live'. Initially, the 'Show Live' checkbox is disabled. I need a feature where if 'Show Active' is checked, it will enable the 'Show Live' checkb ...

Discovering the wonders of Angular's Heroes Tour: What's the magic behind adding the ID in the addHero function

During Angular's official tour of heroes tutorial (https://angular.io/tutorial/toh-pt6), an interesting observation was made. When the addHero method is called, only the hero's name property is passed as an argument. However, it seems that a new ...

The delay in loading HTML content using FOSJsRoutingBundle and Ajax for a specific route parameter (ID)

I'm using FOSjSrouting in my symfony2.7 project. This is the code in my html.twig view: <table> <!--table header code ...etc... --> <tbody> {% for currentData in arrayData %} <tr> <td>{{ currentData. ...

Service in AngularJS not being declared

Attempting to start a service using my controller. controllers.controller('test', function($scope, CalculatorService) { $scope.result = CalculatorService.add(); }); controllers.service('CalculatorService', function(){ this. ...