Repeating every other item in a list using ng-repeat in AngularJS

Using AngularJS version 1.5.3

In my view, I have a list of items that I want to display. After every two items, I would like to show a new div below the first one.

  <div class="col text-center" ng-repeat="event in weekDay.events">
    &nbsp;<small>{{ event.times }}</small>
  </div>

Here is an example of how I want it to look: https://i.stack.imgur.com/mocwa.jpg

I am unsure of how to achieve this using ng-repeat.

Answer №1

What is preventing you from utilizing bootstrap to accomplish this task?

<div class="row">
  <div class="col-xs-6 text-center" ng-repeat="event in weekDay.events">
    &nbsp;<small>{{ event.times }}</small>
  </div>
</div>   

Answer №2

If you want to access the current item index in your ng-repeat loop, you can utilize $index. By checking whether the $index is an odd number, you can decide to display a specific div element. Here is how you can implement it in your code:

<div class="col text-center" ng-repeat="event in weekDay.events">
    &nbsp;<small>{{ event.times }}</small>
    <div class="my-new-div" ng-if="$index%2==1">
       <span>My customized div content</span>
    </div>
</div>

Answer №3

Many agree with the suggestion to use CSS for placing two items in each row, but if you prefer an alternative approach, consider the following:

Determine the number of items in your events divided by the number of items you wish to display in each row (e.g., 2)

  $scope.getNumber = function() {
    console.log($scope.data.length / 2)
    if($scope.data.length % 2 == 0)
      return new Array($scope.data.length / 2);
    else
      return new Array(Math.floor($scope.data.length/2) + 1);   
  }

Adjust your ng-repeat to show the current and next item in each iteration

<div ng-repeat="item in getNumber() track by $index">
    <span>{{data[$index * 2]}}</span> &nbsp;&nbsp;
    <span>{{data[$index * 2 + 1]}}</span>
</div>

Check out the demo.

Answer №4

Try using the code below for a solution:

<div class="col text-center" ng-repeat="event in weekDay.events">
        <div ng-show="$index%2==0">
            &nbsp;<small>{{ event.times }}</small>
            &nbsp;<small>{{ weekDay.events[$index+1].times }}</small>
        </div>
    </div>

Below is a small example to demonstrate how it works:

!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
</head>
<body ng-app="app" ng-controller="ctrl">
<div ng-repeat="event in weekDay.events" style="border:1px solid black">
    <div ng-show="$index%2==0">
        {{event.times}}
        {{weekDay.events[$index+1].times}}
    </div>

</div>

<script src="../lib/angular.js"></script>
<script>
    var app = angular.module('app', []);
    app.controller('ctrl', function ($scope) {

        $scope.weekDay = {
            "events": [
                { "times": "one", "day": "1" },
                { "times": "two", "day": "2" },
                { "times": "three", "day": "3" },
                { "times": "four", "day": "4" },
                { "times": "five", "day": "5" },
                { "times": "six", "day": "6" },
                { "times": "seven", "day": "7" },
                { "times": "eight", "day": "8" },
            ]
        };

    });
</script>

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

Arrange the array based on the order of the enumeration rather than its values

Looking to create an Array of objects with enum properties. export enum MyEnum { FIXTERM1W = 'FIXTERM_1W', FIXTERM2W = 'FIXTERM_2W', FIXTERM1M = 'FIXTERM_1M', FIXTERM2M = 'FIXTERM_2M', FIXTERM3M = 'FIX ...

Using ng-if to test a filter input in Angular

I have created a simple filter that outputs one of two statements based on whether an input from SQL is true or not. app.filter('yesNo', function() { return function(input) { return (input == '1') ? 'Skal tjekk ...

Learn how to transform a raw readme file into an HTML formatted document using AngularJS, after retrieving it from GitHub

Can someone help me figure out how to format each line of the README.MD raw file into an HTML document using the controller below? angular.module('ExampleApp', []) .controller('ExampleController', function($scope, Slim,$sce) { ...

Hover over buttons for a Netflix-style effect

https://i.stack.imgur.com/7SxaL.gif Is there a way to create a hover effect similar to the one shown in the gif? Currently, I am able to zoom it on hover but how can I also incorporate buttons and other details when hovering over it? This is what I have ...

Utilizing several carets in a single or multiple text areas and input boxes

Just a quick question... Can a textbox have two carets simultaneously, or can we have two separate textboxes both focused at the same time? I am aware of simulating this using keydown listeners but I'm specifically looking for visible carets in both ...

The error message "res.jwt is not a function" is commonly encountered when using Node

I kept receiving the error message: res.jwt is not a function I have installed jwt-express and imported it like this: import jwt from 'jwt-express' This is my auth.js file: import Account from '../services/account.js' import env from ...

Organize express controller by breaking it up into multiple separate files

Recently, I've set up an express js controller file as follows The File Path: /controllers/usersController.js // Register User module.exports.register = function(req, res) { ... } // Login User module.exports.login = function(req, res) { ... } // ...

Develop a navigation system with forward and backward buttons to easily navigate between

I'm currently delving into angular and striving to implement a next/back button for showcasing various views. Within my repository, I have a template named example.html <h1>{{ message }}</h1> which is utilized by multiple controllers: ...

SCRIPT5007: The property 'href' cannot be assigned a value as the object is either null or undefined

This script is functioning properly in browsers like Chrome and Firefox, however it is encountering issues when used with Internet Explorer. An error message is displayed in the IE console: SCRIPT5007: Unable to set value of the property 'href': ...

Issues with using the $http call in Ionic Android builds are causing problems

Here is how I am making the call: $http.get( url, { params : { empId: $scope.empId } }).then(function(data, status){ $scope.workOrders = data.data; }, function(data, status){ $scope.message = data; }); It functions perfectly on Ch ...

The JSON.stringify() method does not update the object that has been modified by an event

Below is the code snippet: //function triggered when columns are reordered dataTable.on('column-reorder', function (e, settings, details) { var userData = tableWidget.grid('userData'); console.log(userData); //userData object s ...

What precautions should I take to safeguard my HTML/CSS/JS projects when sharing a link with my employer?

Picture this scenario: you need to share a link for your work, but you want to protect it from being easily copied or developed further by someone else. However, since it's a document, any browser can still view it. Can anyone recommend a tool that wi ...

Tips for successfully transferring the nested service and retrieving the response from an Angular factory to a controller

After making the Http Request and receiving the response from the first Service call, I then pass that response from the first service into the second service and receive the response back to the controller. Now that I have the response, I need to find a ...

Is there a way to serve an HTML file using the response object in expressjs while also incorporating an external JavaScript file?

My express application successfully serves an HTML page from my disk when I initially make a GET request to "http://localhost:3000/" in the browser. Now, I am trying to access a JavaScript file that is located in the same directory on the disk as the HTML ...

The combination of Array.pop and Array.indexOf is not functioning as expected

I'm having an issue with using Array.pop(Array.indexOf(value)). It seems to always delete the last element in the index, even if the value of that index is not what I intended. Can someone provide some guidance on how to resolve this? CheckBoxHandle ...

Link property can be added to a bindpopup polygon in Leaflet to have it open in a new tab when clicked

Is it possible to include a hyperlink in popup content on Leaflet, similar to this example? function onEachFeature(feature, layer) { idLoDat = feature.properties.IDLo; layer.bindPopup("Company name: " + feature.properties.TenCty + " ...

Issues with lazy loading in swiper.js when trying to display multiple images per slide

I recently tried using swiper.js and had success with the lazy loading demo. However, I encountered an issue where only one image per slide was showing up, despite wanting to display 4 images per slide. <div class="swiper-container"> <div cla ...

Update your content dynamically by refreshing it with JQuery/AJAX following the usage of an MVC partial view

Implementing the following JQuery/AJAX function involves calling a partial view when a selection is made in a combobox labeled "ReportedIssue" that resides within the same partial view. The div containing the table is named "tableContent". <script type ...

Vue automatically populates an empty array with an Observer object

I have been attempting to create an empty array in the data and then fetch a JSON from the server to populate it. The issue I am encountering is that the array consistently includes an extra Observer object, so when I log it, I see: empty items array: ...

Using ChartsJs to visualize input data formatted in the German data format

I am relatively new to working with Charts.js, but I will need it to generate some visually appealing graphs for my website. In the background, I have a Django project running that calculates a specific set of numbers for me. Due to the language setting in ...