What is the best practice for adding a DOM element at a precise location within an ng-repeat loop?

I am currently working on developing a podcast player application using AngularJS.

At this point, I have successfully created a list of available podcasts that can be played, utilizing ng-repeat. The code for the list is shown below:

<ul ng-controller="list">
  <li ng-repeat="podcast in podcasts" ng-click="startPlaying()">
    <p>{{podcast.created_time | date}}</p>
    <div class="podcast-icon" style="background-image:url('{{podcast.icon}}')">
      <i class="fa fa-play"></i>
    </div>
    <h3>{{podcast.name}}</h3>
    <p>{{podcast.duration}}m</p>
  </li>
</ul>

These podcasts are displayed in a responsive flexbox grid layout. When a user clicks on a podcast, I want the function startPlaying to trigger a player to appear right below the clicked item, similar to how it works on Netflix.

I have two main questions regarding this functionality:

  1. How can I determine the index of the <li> element at the end of the row where the clicked element is placed, considering the responsiveness of the grid and the varying number of <li>s per row?
  2. Is there a way in AngularJS to insert a new DOM element after a specific index within an ng-repeat loop?

One approach I have considered is deriving the number of <li>s per row by inspecting the width of the parent container using

window.getComputedStyle(ul).width
. However, I believe there might be a more efficient method to achieve this. Any suggestions would be greatly appreciated!

Thank you!

Answer №1

To access the index of the li, you can use the following methods:

{{$index}}

or alternatively:

{{podcasts.indexOf(podcast)}}

If you include this in your click event, you can then add an element within the corresponding function like so:

<li ng-repeat="podcast in podcasts" ng-click="startPlaying($index)">

It's important to identify the correct element by giving the li a class:

<li class="podcast" ng-repeat="podcast in podcasts" ng-click="startPlaying($index)">

Then in your startPlaying function, you can select the element by its index and append your desired element:

$scope.startPlaying = function(index) {
  var podcasts = document.getElementsByClassName('podcast')
  var currentPodcast = podcasts[index]
  angular.element(currentPodcast).append('<html></html>');
}

Simply replace <html></html> with the element you wish to append.

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

The 'mat-table' component is triggering an error indicating that the 'dataSource' attribute is unrecognized in the table

Recently, I have been diving into the world of Material Library for Angular. Working with Angular version 15.0.1 and Material version 15.0.1, I decided to include a mat-table in my form (schedule.allocator.component.html): https://i.stack.imgur.com/c7bsO. ...

Forwarding the geographic coordinates directly to the system's database

I have a unique script that retrieves the precise latitude and longitude position. It then automatically sends this data to a database without the need for user input. <script> function getPosition(position) { var latitude = position.coor ...

Tips for assigning a Custom Formik Component's value to the Formik value

I'm currently integrating Formik into my form alongside Google Places auto-complete feature. My goal is to display the places auto-complete functionality as a custom component within the Formik field. form.js <Formik initialValues={location:" ...

`Adjusting function calls based on the specific situation`

On my webpage, I have implemented a tab system where clicking on a tab displays the corresponding content below. This functionality is controlled by a JavaScript/jQuery function called 'changeTab'. Now, I want to set up individual JavaScript fun ...

Styling and scripting with CSS and jQuery in an external JavaScript file

Is it possible to add the jquery library from "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" into an external .js file? And how can a .css file be included in a .js file? ...

Using Array Data Binding in SAPUI5 for Lists

I am looking to connect a list along with its content to a model. var listItem = new sap.m.StandardListItem({ title: "{carDataModel>/cars/1/carId}", }); var list = new sap.m.List("carList", { }); list.bindItems('carDataM ...

Customize Joomla content in a component by using CSS within a template that I personally designed

Is there a way to customize the text content of a component in Joomla by editing the body text? The CSS properties for #content are adjusting padding, margin, border, width, height, and background but not affecting font attributes... Inside index.php < ...

Setting a div to occupy the entire height of a webpage using HTML and CSS

Is there a way to make the div (the blue box) fill the entire page? I tried setting the body tag to height:100%, but it didn't work. You can view an example at http://jsfiddle.net/rVyrX/1/ ...

Facing problem with implementing NgMoudleFactoryLoader for lazy loading in Angular 8

A situation arose where I needed to lazy load a popups module outside of the regular router lazy-loading. In order to achieve this, I made the following adjustments: angular.json "architect": { "build": { ... "options": { ... "lazyM ...

Navigating through embedded arrays in Angular

JSON Object const users = [{ "name":"Mark", "age":30, "isActive" : true, "cars":{ Owned : ["Ford", "BMW", "Fiat"], Rented : ["Ford", "BMW", "Fiat" ...

In Javascript, async functions automatically halt all ongoing "threads" when a new function begins

I have a dilemma with multiple async functions that can be called by the user at any point in time. It is crucial for me to ensure that all previously executed functions (and any potential "threads" they may have initiated) are terminated when a new functi ...

Exploring location-based services using React-Redux

Seeking a deeper comprehension of redux and the react lifecycle methods. The issue I am facing involves a prop function within the componentDidMount that calls another function in redux. Within redux, I attempt to retrieve location data to set as the init ...

Issue with page break functionality during print preview

div.pagebreak { page-break-after: always; page-break-inside: avoid; } HTML <!-- Page separator --> <div class="pagebreak" style="float: none;"><hr class="hidden-print" /></div> <app-mud-chec ...

Deno -> What steps should I take to ensure my codes run smoothly without any errors?

Trying to import locally Experimenting with Deno v1.6.0 in a testing environment Attempting local imports using Deno language Local directory structure: . └── src └── sample ├── hello_world.ts ├── httpRequest. ...

How can I adjust the appearance of an HTML tag within an Angular component?

I have created an Angular component with the following definition: import { Component, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'rdc-dynamic-icon-button', templateUrl: './dynamic-icon-button. ...

Elevating the Material Design Lite Progress bar using ReactJS

I currently have MDL running with React and it appears to be functioning properly. The Progress Bar is displaying on the page as expected, loading with the specified progress on page load when a number is entered directly: document.querySelector('#qu ...

I'm running into an issue with my React component where it is rendering before the state is set, causing it to fail. Is there a

Is it possible for me to achieve what I've been attempting for the past week? I feel like I'm so close, yet still can't quite reach my goal. Could it be that what I'm trying to do is impossible? I am using reactjs and next js (although ...

Getting the parameters of a path from the URL's breadcrumb in Vue.js

Currently utilizing Vue Attempting to include path parameters in breadcrumb URLs for my app's router. Looking to achieve something similar to the following: { path: 'pages/gestion/region/:reg', name: 'gestion-depa', ...

Confusing postback phenomena in ASP.NET web forms

I have developed a small script that successfully maintains the focused element during an async postback. However, I encountered an issue when tabbing through controls generated inside an asp:Repeater, where a full postback is unexpectedly triggered. Below ...

I am currently working with CakePHP and am interested in learning how to expire the admin session

I'm having issues with the code in my UserController. When I open the admin panel in two tabs within the same browser and log out from one tab, I am unable to redirect to the login page from the other tab when clicking on any menu. function beforeFil ...