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

Setting null for HttpParams during the call

I am encountering an issue with HttpParams and HttpHeaders after upgrading my project from Angular 7 to Angular 8. The problem arises when I make a call to the API, as the parameters are not being added. Any assistance in resolving this matter would be gre ...

Changing the format of a numerical value to include commas for every 1000 increment

I'm trying to find a way to format numbers in a specific manner, such as changing 1234567 into 1,234,567. However, I've run into some issues when attempting to use the currency pipe of TypeScript. It adds USD or $ in front of the number, which i ...

What steps can be taken to override the property overflow:hidden specifically for a custom tooltip design

I am facing a challenge with overriding the property overflow:hidden in the parent td element. https://i.stack.imgur.com/HKcvn.png This issue is related to my tooltip, which ideally should be displayed beneath the td element: Code snippet for the toolti ...

Manipulate sibling elements using jQuery's addClass and remove methods

I have implemented a function that adds the class active to elements when they reach the top of the browser, ensuring that the next element will scroll in over the top. While this works smoothly in Chrome, I am encountering some jumping behavior when testi ...

Update the page by selecting the refresh option from the drop-down menu

In my script, I have different views showing information retrieved from a database. One view displays the quantity of a product sold each month, another shows sales, the third presents profits, and the last exhibits calculated percentages using sales and p ...

Clearing Up CSS Height Definitions

Based on my observations from other posts, it seems that to establish the height of an element in percentages or pixels, etc., the parent element's height also needs to be explicitly defined. This implies that the height settings must be specified all ...

Arrays data being retrieved and set by Chrome Extension are visible in the console but not appearing in the HTML

Having trouble displaying my arrays in HTML. I'm attempting to do this within a Chrome Extension. While I can view the array perfectly in console.log, I'm encountering issues when trying to add it to the HTML DOM: /* Generating the array f ...

Verify if the item already exists in the Vue.js array

Here is the data I have: data: function() { return { conversations: [ ] } } I am retrieving my data from the response object using response.data.conversation Is there a method to verify if this.conve ...

Is the CSS Transition Solely Active for the Introductory Animation?

I'm currently looking to enhance the smoothness of div expansion and contraction on hover using CSS transitions. However, I have noticed that the Transition property only seems to affect the entry animation (i.e., when the mouse hovers and the div exp ...

Getting Started with CSS Alignment - A Novice's Guide

Recently, I embarked on my journey to learn HTML and CSS with the ambition of creating a login page. Although I've successfully crafted a basic version, I'm encountering an issue where the input boxes and labels are misaligned, giving off an unpr ...

Can the line "as is" be included in HTML code?

Can I incorporate the following JavaScript and JSON expressions directly into HTML code? CONTRATE > 50 && SALINC <= 50 || RETAGE >= 50 { "CONTRATE": 0, "SALINC": 0, "MARSTATUS": "single", "SPOUSEDOB": "1970-01-01" } I want to be able to ...

How to specify columns when storing data in a CSV file using Scrapy

As I scrape data from the web, I am facing an issue with my csv file where the links column is always displayed as the first column. How can I specify the placement of columns in the csv file? pName = response.css('#search .a-size-medium') ...

Challenges with implementing emotion in Material UI 5

Recently, I upgraded my react app from Material UI 4 to 5 Beta. After consulting the documentation on the docs style library, I learned that the new version allows the use of emotion. However, when I attempted to implement it, I encountered an issue with t ...

What is the reason behind the unnecessary requirement of adding {...props} when passing them to a component in a React router?

Recently, I delved into learning React and encountered a puzzling issue while following a course. To gain clarity, I decided to experiment with it separately, but the confusion remains unresolved. While researching, I discovered that when utilizing a Rout ...

I am facing difficulties accessing an element within a controller in Angular

Struggling to access an element inside an AngularJS controller, I attempted the following: var imageInput = document.getElementById("myImage"); Unfortunately, this approach was unsuccessful as the element returned null. Curiously, when placing the statem ...

Using jQuery's .html function to insert images

I have a unique counter that counts in currencies, such as Yen and Euro. Each number, as well as the currency sign and separator, are all displayed on the webpage using custom-designed icons. I utilize the display: flex; property in my container div and ap ...

What is the best way to arrange a number of inline-block elements with equal size in a vertical alignment?

My goal is to display a set number of items in a container, all with the same fixed size. The challenge arises when the content of each item varies in length, causing misalignment vertically: .child { display: inline-block; background: #bbbbbb; marg ...

Adjust the sizes of the points according to the level of zoom

I've been working on creating a dynamic map in d3.js that displays US Science funding agencies as points, with their sizes scaling based on zoom level. I referred to this starter kit for guidance. While there are other solutions out there, they often ...

Ways to access information received from AngularJS in a different Javascript file

I am currently using Angular to retrieve output from a controller and display it using ng-bind. However, I have another separate JavaScript file that needs to utilize a value returned from Angular. In the example code provided below, the TestAppCtrl is ca ...

retrieve information instantly on AngularJS by utilizing $http or $resource

I designed a plugin for field customization. angular.module('ersProfileForm').directive('ersProfileEditableField', ['$templateCache', '$compile', 'profileFieldService', 'RolesService', ...