How to Insert <ul></ul> After Every Other <li> Element Using Angular's ngRepeat

With my current setup, I have a list item (li) within a list (ul) and applied ngRepeart. However, I would like to create a new ul after every 2nd li. Is this possible with AngularJS?

<ul>
  <li>simth</li>
  <li>aryan</li>
</ul>
<ul>
  <li>john</li>
  <li>mark</li>
</ul>
<ul>
  <li>cooper</li>
  <li>lee</li>
</ul>

This is the code for my AngularJS:

function myCrtl($scope){
  $scope.nameList= [{
      name:'simth'
    },{
      name:'aryan'
    },{
      name:'john'
    },{
      name:'mark'
    },{
      name:'cooper'
    },{
      name:'lee'
    }]
}

Answer №1

Working with AngularJS involves a concept similar to "Data Driven Development". Aligning your data with the desired HTML structure may pose challenges, but it's certainly not insurmountable. One approach is to modify the structure of your data. If that's not feasible, consider exploring other options.

const myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', $scope => {
    $scope.nameList = [
        [{name: 'simth'}, {name: 'aryan'}],
        [{name: 'john'}, {name: 'mark'}],
        [{name: 'cooper'}, {name: 'lee'}]
    ];
    
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl">
    <ul ng-repeat="group in nameList">
        <li ng-repeat="person in group">{{person.name}}</li>
    </ul>
</div>
</div>

Another Approach

If altering the data structure is not an option, you can implement a helper function or filter:

const myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', $scope => {
    $scope.nameList = [
        {name: 'simth'},
        {name: 'aryan'},
        {name: 'john'},
        {name: 'mark'},
        {name: 'cooper'},
        {name: 'lee'}
    ];
});

myApp.filter('getGroup', () => (array, number) => {
    return array.reduce((prev, next, index) => {
        if (index % number === 0) {  
            prev.push([next]);
        } else {
            prev[prev.length - 1].push(next);  
        }
        return prev;
    }, []);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl">
    <ul ng-repeat="group in nameList | getGroup:2">
        <li ng-repeat="person in group">{{person.name}}</li>
    </ul>
</div>
</div>

The purpose of the filter is to segment the array into subarrays, each containing 2 elements (adjustable based on your needs).

Answer №2

It's advisable to reorganize your data as suggested by others, however, if you really insist, you could implement a solution like the one below:

<ul ng-if="$even" ng-repeat="person in nameList">

    <li>{{ person.name }}</li>
    <li>{{ nameList[$index + 1].name }}</li>

</ul>

With the ng-if directive, only every other item in your list will be displayed.

Answer №3

While I do agree with Miszy, there is another way to accomplish this task using the code snippet below:

<section ng-repeat="element in myList">
                <ul ng-if="$index%3 == 0">
                    <li ng-repeat="item in myList.slice($index, $index+3)">
                        {{ item.name }}
                    </li>
                </ul>
            </section>

Answer №4

You have the option to divide your array into sections. Check out the demonstration provided below:

var application = angular.module('application', []);

application.controller('mainCtrl', function($scope) {


  $scope.listOfNames = [{
    name: 'Smith'
  }, {
    name: 'Aryan'
  }, {
    name: 'John'
  }, {
    name: 'Mark'
  }, {
    name: 'Cooper'
  }, {
    name: 'Lee'
  }]

  Array.prototype.chunk = function(size) {
    var arr = this;
    return [].concat.apply([],
      arr.map(function(element, index) {
        return index % size ? [] : [arr.slice(index, index + size)];
      })
    );
  }

  $scope.arrayTemp = $scope.listOfNames.chunk(2)


});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="application">
  <div ng-controller="mainCtrl">

    <ul ng-repeat="group in arrayTemp">
      <li ng-repeat="individual in group">{{individual.name}}</li>
    </ul>
  </div>
</div>

Answer №5

Here's a way you can store your list:

function myController($scope){
  $scope.peopleList= [{
      first:'Alice',
      last: 'Smith'
    },{
      first:'Bob',
      last: 'Johnson'
    },{
      first:'Charlie',
      last: 'Brown'
    }]
}

You can then use ng-repeat to display the list easily:

<div ng-repeat-start="person in peopleList">
  <ul>
    <li>{{ person.first }}</li>
    <li>{{ person.last }}</li>
  </ul>
</div>

Answer №6

If you want to change the input list format, there are various possibilities provided by others that you can explore. I recommend taking a look at the general approach shared in this jsfiddle link.

I have created a function that transforms your input list into the specified format:

$scope.getSegment = function(noOfRecord){
    noOfRecord = noOfRecord;
    var processedList = [];
    var tempList = [];
    for(var i = 0; i <  $scope.nameList.length; i++){
        tempList.push($scope.nameList[i]);
        if((i+1)%noOfRecord == 0){
            processedList.push(tempList);
            tempList = [];
        }
    }
    return processedList;
};

You can loop through it like this:

<ul ng-repeat="group in getSegment(2)">
    <li ng-repeat="detail in group">{{detail.name}}</li>
</ul>

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

What steps can I take to improve this code and prevent the error "Property 'patient' does not exist on type 'Request<ParamsDictionary>'" from occurring?

I'm having some issues with my code. I am attempting to use passport authenticate in order to save patient information that is specific to the token generated for each individual. router.get("/current", passport.authenticate("jwt", { session: false }) ...

Behat automates the process of populating form fields that are dynamically displayed as 'visible'

I'm facing an issue with a form that has hidden fields. When a user selects a checkbox, some of the hidden form fields are supposed to be revealed using the jQuery function slideToggle(). The code itself is pretty simple and you can see an example her ...

The getStaticProps function will generate an object by fetching data from various URLs

Within my getStaticProps function in next js, I am faced with the challenge of fetching multiple dynamic URLs and exporting the results as props to the component. As these URLs are automatically generated, I do not know how many there will be to fetch. My ...

When attempting to use focusin/focusout, I encountered the following error: Uncaught TypeError - The property 'addEventListener' cannot be read from null

When attempting to utilize the DOM events focusin/focusout, I encountered an error: Uncaught TypeError: Cannot read property 'addEventListener' of null. The issue seems to be originating from main.js at lines 18 and 40. I am using Chrome as my b ...

Generating a new root in React 18 results in numerous rounds of rendering and execution

Every time I attempt to run this code in React 18, it seems to render multiple times unlike React 17 where it only executes once and functions properly. How can I modify the code so that it only runs once? Is there a specific reason for the multiple execu ...

Error: Cannot access 'addEventListener' property of null in Chrome Extension due to TypeError

I've been working on developing a chrome extension that autofills input forms in web pages. However, I encountered an error that says "cannot read properties of null." This issue arises when I try to add an event listener to a button in my code. The f ...

Update the value after verifying the element

I am trying to retrieve data from my database and update the values when an element is clicked (accepting user posts). The code I have written seems to work, but I encounter an error stating that props.actions is not a function when clicking on an element. ...

How do I go about configuring the uploaded image?

Here is a sample of my HTML code: <div class="images"> <figure> <button id="upload-add-product" class="icon-plus"></button> <input id="upload-file" type="file" style="display: none;" multiple/> </fi ...

What is the functionality of ng-repeat in AngularJS when used outside the "jump" table?

Currently, I am in the process of constructing a layout using a table with nested ng-repeat. <div ng-controller="PresetManageController"> <table> <in-preset ng-repeat="preset in presetManage.presets"></in-preset> </table ...

Tips for retrieving document body from a script embedded within document.write

I urgently need assistance! I am currently developing an application that retrieves a report from an API, and the JSON response includes HTML content. Unfortunately, due to the JSON format, I cannot directly open this in a new browser window. Within my sc ...

Is it possible to incorporate an editable text feature within react-moveable? (Allowing for both dragging and editing capabilities)

In React Movable box, the text can be dragged with a left click and edited with a right click using the "contentEditable" attribute. However, on smartphones, editing seems to be disabled and only dragging is possible. <div className="move ...

Retrieve targeted HTML content using AJAX from a webpage that is already being fetched via AJAX

Looking to load a specific div on my webpage via Ajax call, but the content I want to load is itself loaded via ajax. This means I can't get the full HTML content as desired. function loadajax(){ $.ajax({ url: 'http://callcom-com-au.myshopify. ...

Customize the size of innerWidth and innerHeight in your THREEjs project

Is there a way to customize the size of the window where this function launches instead of it automatically calculating the height and width? I've attempted to modify this section of the code, but haven't had any success so far: renderer.setSiz ...

What is preventing the value from changing in auth.guard?

I am encountering an issue with the variable loggined, which I modify using the logTog() method. When I call this method, a request is made to a service where the current result is passed to auth.guard. However, in the console, it displays "undefined". Can ...

What is the best way to manage variables that are not present in a Vue.js template?

When working with vue.js templates, I often come across instances like this: {{ jobs[0].stages[0].node.name }} If a job has no stages, the entire template fails to load and vue.js admin throws this warning: Error in render: "TypeError: Cannot read prope ...

Updating the ID's of nested elements in JavaScript when duplicating an element

After a fruitless search on Google, I have turned to the experts on SO for assistance. The challenge: Create a duplicate of a dropdown menu and an input field with the click of a button (which can be done multiple times) The proposed solution: Implement ...

Attributes for 'v-bind' directives must have a value specified

Struggling to implement a tree structure in vue.js and encountering an issue with element props. Any assistance would be greatly appreciated. I've attempted using :content="{{tempCont}}" as well as content="{{tempCont}}", but neither approach proved ...

Exploring the synergies of Next.js and Node.js thread pooling

In my current project, I am utilizing nextJS with NodeJS and looking to implement child processes or workers. The code provided by NextJS itself is functioning perfectly. The relevant code snippets: NextJS with NodeJS Another resource I referred to: Nex ...

Guide to creating a functional Async API

I am currently facing a challenge while developing an application for my institution. I need to allow users to access database information (currently using firebase) from an external server, so I set up a node.js server to facilitate communication and hand ...

Is the performance impacted by using try / catch instead of the `.catch` observable operator when handling XHR requests?

Recently, I encountered an interesting scenario. While evaluating a new project and reviewing the codebase, I noticed that all HTTP requests within the service files were enclosed in a JavaScript try / catch block instead of utilizing the .catch observable ...