Utilizing the powerful combination of AngularJS and Ionic, leverage the ng-repeat feature to seamlessly insert elements between

There are 2 loops in our code structure. They look like this:

<ion-list>
  <ion-item ng-repeat="pair in items">
      <div class="row">
          <ion-item ng-repeat="item in pair" class="col-45">
              {{item}}
          </ion-item>
      </div>
  </ion-item>
</ion-list>

I am looking to add an element between items in the second loop, specifically with a class of col-10. What would be the optimal approach to achieve this? Is there a way to modify ng-repeat to include a custom element between iterations? Or perhaps replace it with a traditional for loop?

The desired final layout is as follows:

<div class="row"> 
  <div class="col-45"></div>
  <div class="col-10"></div>
  <div class="col-45"></div>
</div>

UPD: The controller sends an array called pair containing [1,2]. The expected result should be:

<div class="row"> 
  <div class="col-45">1</div>
  <div class="col-10"></div>
  <div class="col-45">2</div>
</div>

Answer №1

Revised Solution:

After some consideration, I came up with a solution using jQuery without the need for additional divs. However, I am still exploring potential ways to achieve the same outcome in pure Angular, possibly through a directive or ng-include. Here is the revised approach:

<ion-list>
      <ion-item ng-repeat="(parentIndex, pair) in items">
          <div class="row">
              <ion-item ng-repeat="item in pair"
                        class="col-45 item-{{parentIndex}}-{{$index}}"
                        ng-init="insertAfter(parentIndex, $index)">
                  {{item}}
              </ion-item>
          </div>
      </ion-item>
  </ion-list>

In the controller, you would have something like this:

$scope.items = [
   [ "someValue", "someOtherValue" ],
   [ "someValue", "someOtherValue" ]
];

$scope.insertAfter = function(parentIndex, index){
   if(index < $scope.items[parentIndex].length){
       $timeout(function(){
           jQuery( "<div class='col-10'> or maybe include a template here </div>" )
                 .insertAfter(".item-"+parentIndex+"-"+index );
       }, 0);
   }
};

If you intend to insert directives, it's essential to compile them first. Therefore, a directive that handles these actions would be preferable over relying solely on the controller.

Initial Approach:

Previous method was more of a quick fix rather than a comprehensive solution

<ion-list>
   <ion-item ng-repeat="pair in items">
       <div class="row some-container">
           <div ng-repeat="item in pair">
               <ion-item class="col-45">
                   {{item}}
               </ion-item>
               <div class="col-10"></div>
           </div>
       </div>
   </ion-item>
</ion-list>

.some-container div.col-10:last-child { display: none; }

Although the markup may not align precisely with your requirements, it could provide some assistance.

Answer №2

To implement conditional classes in AngularJS, you can leverage the $odd property with ng-class. Here is an example of how you can achieve this:

<ion-list>
 <ion-item ng-repeat="pair in items">
  <div class="row">
      <ion-item ng-repeat="item in pair" ng-class="{true:'col-45', false:'col-10'}[$odd]">
          {{item}}
      </ion-item>
  </div>

Alternatively, you can use ng-class-odd and ng-class-even directives for applying odd and even classes:

<ion-list>
 <ion-item ng-repeat="pair in items">
  <div class="row">
      <ion-item ng-repeat="item in pair" ng-class-odd="'col-45'" ng-class-even="'col-10'">
          {{item}}
      </ion-item>
  </div>

Here's a working example: http://plnkr.co/edit/Ueawsp9Xc7Ri8qKwLQ1N?p=preview

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

Questions about setting up a controller in AngularJS

As I dive into my first AngularJS controller within a test application, I am encountering some challenges. I am retrieving a list of items from a RESTful web service and working on implementing basic CRUD logic for these items. The item list is displayed ...

Guide on transforming an array into a Collection

I have a text file in the format shown below. ID;SubID;No.;Name;Min;Max;Default;Factor;Unit 101;5;0;Gas flow time;0;100;0.1;10;s 101;30;1;Start speed;20;200;120;1;m/s ;;2;Start current;0;999;1.0;10;A I am reading this text file using the npm package & ...

What is the maximum length for the string that can be passed to jQuery's .append() method?

In Angular, I developed a simple program that leverages router functionality to showcase two pages within a single-page application. The setup includes a page with two navigational buttons and a wrapper div (ng-view) that dynamically displays the content o ...

Arranging two <ul> elements within an angular template

I need assistance with aligning two ul blocks. Currently, they are displaying next to each other, but their alignment is starting from the bottom instead of the top: <div class="ingredients-container"> <div style="display: inline-block; width: ...

Navigating to an API endpoint while iterating through an ng-repeat loop

I am currently working with an API that provides a list of values. My goal is to enable users to click on the name of a driver in the API and be directed to specific details related to that driver. However, I am struggling to figure out how to implement th ...

Developing a unique JavaScript object by extracting information from a jQuery AJAX response

Is there a recommended approach for creating a custom JavaScript object that contains data retrieved from a jQuery AJAX request? I'm considering two methods, but unsure which is the most appropriate. The first method involves including the AJAX reques ...

Following an AJAX request, jQuery.each() does not have access to the newly loaded CSS selectors

Note: While I value the opinions of others, I don't believe this issue is a duplicate based on the provided link. I have searched for a solution but have not found one that addresses my specific problem. Objective: Load HTML content to an element u ...

Restricting the Vue for-loop results to display only the current item in use

Currently, I am utilizing a for-loop to retrieve all of my posts, followed by employing a partial to obtain a list of all the usersThatUpvoted on that post. <div v-for="p in posts" style="padding: 16px"> <div> &l ...

Guide for sending a JSON object as a parameter from an AngularJS frontend to a WebAPI method and fetching the data

I am facing an issue with passing data from an AngularJS front end to a WebAPI and retrieving another set of data to display on a grid. I have been attempting to pass the data as a JSON object to the WebAPI method, where the parameter being passed is a Cla ...

Suggestions for deleting browser cache programmatically by utilizing JS or HTML

Having trouble clearing the Chrome browser cache using Add-ons. Working on a site development project using JSP with Java, it's crucial for security reasons to clear the cache. Tried multiple methods but none have been successful. Any suggestions? Ple ...

Ways to extract text solely from the parent element, excluding any content from the child elements

I need to extract just the text updated page title from the following code snippet <h2 class="cmp-title__text" xpath="1"> updated page title <span class="gmt_style" aria-hidden="true"&;gt; ...

What could be causing the QullJS delta to display in a nonsensical sequence?

The outcome showcased in the delta appears as: {"ops":[{"retain":710},{"insert":" yesterday, and she says—”\n“The clinic?","attributes":{"prediction":"prediction"}},{"del ...

Unable to add or publish text in CKEditor

In my ASP.NET MVC application, I am struggling to post the updated value from a CKEditor in a textarea. Here is the code snippet: <textarea name="Description" id="Description" rows="10" cols="80"> This is my textarea to be replaced with CKEditor ...

Utilize AngularJS and Java Spring to submit form data

I am facing an issue with my JSP file while uploading a file. I have created a Spring controller for handling the backend of the uploaded file, but I keep getting an error in the console saying String parameter 'name' is not present. Below is the ...

Flowtype: Utilizing type hints for class-based higher order component

I am currently working on typehinting a higher-order component (HOC) that adds a specific prop to a passed Component. The code snippet looks like this: // @flow import React, { Component } from 'react'; import type { ComponentType } from 'r ...

What is the best way to customize the link style for individual data links within a Highcharts network graph?

I am currently working on creating a Network Graph that visualizes relationships between devices and individuals in an Internet of Things environment. The data for the graph is extracted from a database, including information about the sender and receiver ...

Conditional hiding of navigation button based on the current state transition

Is it possible to dynamically hide or show the button based on my current view? <ion-nav-buttons side="right"> <button id="search_button" class="button button-icon ion-ios-search button-clear" ng-click="search()"> </button> ...

Attempting to set up Prettier in my VSCode environment

I've been delving into JavaScript with the guidance of "Morten Rand-Hendriksen" on LinkedIn Learning. The instructor emphasized the importance of installing "Prettier" in our VSCode environment. Following his instructions, I headed to the "Extensions" ...

Troubleshooting Parallax Logic in NextJS

import Head from 'next/head' import styles from '../styles/Home.module.css' import Image from 'next/image' import React, { useRef ,useEffect, useState } from 'react'; export default function Home() { let ref = use ...

What is the best way to populate an array with unique values while applying a condition based on the objects' properties?

Looking to create a unique exam experience for each student? I have an array of question objects and the goal is to select random and distinct questions from this array until the total sum of scores equals the specified exam score. This means that every s ...