How to target individual DOM elements using their id within an ng-repeat loop in AngularJS

In a unique scenario I find myself in, there is a need to modify the CSS within a controller. While not typically recommended, it is necessary for this specific situation as outlined below.

Within an ng-repeat loop, I have a title and description housed inside list elements. The goal is to apply a CSS class to the description based on the height of the title div.

However, attempting to retrieve the height of the 'title' div by id within the controller always returns the height of the first element. This issue becomes evident when trying to access the text of the title. The controller logic is presented as:

$scope.getClass = function() {

     var title = document.getElementById('title');
    var titleHeight = window.getComputedStyle(title, null).getPropertyValue("height");
     var titleText = document.getElementById('title').textContent;
    
     if(titleHeight == '50px') {
       return 'description-small';
     }
      else if(titleHeight == '25px') {
       return 'description-large';
     }

};

The corresponding HTML code is structured as follows:

<ul>
  <li class="li-element" ng-repeat="item in itemList">      
     <div id="title" class="title" data-ellipsis data-ng-bind="item.title"></div>
     <div class="{{getClass()}}" data-ellipsis data-ng-bind="item.description"></div>    
   </li> 
</ul>

This results in subsequent descriptions inheriting the height set for the first item's title, regardless of its actual size.

The behavior seems related to how ng-repeat functions, and being relatively new to this, I am unsure how to address it - any suggestions?

A demonstration of the problem can be viewed here: http://plnkr.co/edit/G1QEq62CbJ0HpNZ0FfSm

REASON FOR MANIPULATING DOM IN CONTROLLER:

The challenge arises from dealing with dynamic content where the height of the title fluctuates based on the length. To maintain consistency, both the title and description have a combined height limit of 125px. However, due to uncertainty regarding the title's height, determining the appropriate height for the description proves challenging. The 'data-ellipsis' directive relies on CSS-defined heights.

Hence, the necessity to dynamically adjust the description class based on the title's height. If there are alternative approaches to resolve this, I am open to exploration!

For reference, here is the link to the data ellipsis directive utilized: https://github.com/dibari/angular-ellipsis

Answer №1

One issue arises from assigning the same id to multiple divs. getElementById will only retrieve the first div with id title. To solve this, simply add an index to each id. By utilizing ng-attr-id, unique ids can be generated dynamically for every div within the ng-repeat block. The $index variable provides the current index in the ng-repeat block, which is then passed to the getClass function to specify the corresponding title.
Plunkr

CODE UPDATES

ng-repeat

<li class="li-element" ng-repeat="item in itemList">

            <div ng-attr-id="{{'title'+$index}}" class="title" data-ellipsis data-ng-bind="item.title"></div>

            <div class="{{getClass($index)}}" data-ellipsis data-ng-bind="item.description"></div>

 </li>

getClass

$scope.getClass = function(i) {

        var title = document.getElementById('title'+i);
        var titleHeight = window.getComputedStyle(title, null).getPropertyValue("height");
        var titleText = title.textContent;

        if(titleHeight == '50px') {
            console.log("titleheight = 62px");
            console.log("titleText = " + titleText);
            return 'description-small';
        }
        else if(titleHeight == '25px') {
            console.log("titleheight = 31px");
            console.log("titleText = " + titleText);
            return 'description-large';
        }

    };

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

Launching ng-app for AngularJS after the page has finished loading

After loading content with jQuery AJAX that includes ng-app="" and other directives, the AngularJS initialization does not occur. How can I initialize an ng-app that was added after the page has already been loaded? <script src="https://ajax.googleap ...

Ways to integrate a CSS file into XSLT

I have a CSS file that looks like this: .table_class1DeffCell { border-top-width : 1; border-left-width : 1; border-right-width : 1; border-bottom-width : 1; } .table_class11DeffCell { border-bottom-color : 000000; border-top-color : 000000; border-right- ...

Is it possible to include a div above a centered image?

Currently I am working with ImageFlow and I would like to overlay a div on top of the image when it is clicked, sliding it into the center. I have been looking through the JavaScript file but the function MoveIT() seems to be called multiple times and I am ...

Overlap in Shield UI Bar Chart

I am looking to create a unique bar chart using Shield UI that features two bars overlapped, rather than side by side. I do not want the total Y axis value displayed. While an area chart accomplishes this, I am specifically interested in achieving this e ...

Combining arrays by a shared property in JavaScript

My goal is to merge data from two arrays based on the userId. The current solution I have only works efficiently with small datasets, but it becomes impractical with larger arrays due to the excessive use of the filter method. Does anyone have a more effic ...

Can anyone suggest a method to display a line above every individual bar on a bar chart?

I have a bar Chart and I am looking for a way to display a horizontal line above the bar to show the peak value. Is there any method within echarts that can achieve this without needing a custom renderer? var myChart = echarts.init(document ...

Verify the status of the internet button and display a message indicating whether it has been selected or not

I’ve been attempting to complete this task: opening this particular page in Python, and observing the outcome when the "Remote eligible" button is enabled; do any job positions appear or not? Here's the code I have so far, but it keeps throwing thi ...

What is the best way to begin the main page content below the stationary header in order to prevent any overlap with the hyperlink section?

I have created this HTML page, but I am facing an issue where the hyperlinked sections overlap with the static header when clicked on. I want all linked sections to appear below the header and each section to have different dimensions within the iframe. I ...

Ensure to wait for the user ID before accessing Firestore collections

Trying to wrap my head around rxJs and experimenting with using the where query in Firestore collection. However, I've run into an issue where the output of this collection is dependent on retrieving the user ID from Firebase Auth. Here's what I ...

Error: The function `map` cannot be applied to `cardsData`

I'm encountering an issue where I need to store user queries in cardsData and then map through the data within cardsData. However, when I run the code on my terminal, it throws an error. As a beginner, I've researched various forums that mention ...

Preserve the button interface when it is clicked

Just diving into the world of CSS for the first time with a front end styling task, so apologies in advance for any errors or misunderstandings! I have a placeholder button that triggers a Modal (1): https://i.sstatic.net/1wT9Y.png When clicked, the but ...

Investigating methods for troubleshooting unresponsive JavaScript that is failing to retrieve information from MongoDB

Currently, I am actively engaged in the steps outlined in this helpful tutorial: Data Visualization Tutorial Despite successfully troubleshooting various issues along the way, I am encountering a challenge where the data from MongoDB is not being displaye ...

In Firefox, there is a peculiar issue where one of the text boxes in an HTML form does not display

In my HTML form, users can input their first name, last name, and phone number to create an account ID. The textboxes for first name, last name, and account ID work smoothly on all browsers except Firefox. Surprisingly, the phone number textbox doesn' ...

Retrieve the attribute of the clicked element by utilizing the on click event handler

Within my HTML, there is a page displaying approximately 25 thumbnails, each with a like button in this specific format: <input type="button" class="btn btn-primary btn-small" id="likeBtn" data-id="545206032225604" value="Like"> It's important ...

The aspect ratio of a DIV element is not maintaining its scale properly in Firefox

My current challenge involves using a Script to Scale a Div while maintaining the aspect ratio. The objective is to ensure that 100% of the DIV remains visible while maximizing its size. As you scale the browser width, the div adjusts its height to 100%, a ...

Sending non-textual data within a JQuery ajax POST request

I have encountered an issue related to sending data from a JavaScript application to a Node.js server for database query purposes. Despite trying to find a solution from various sources, I have been unable to resolve it. Here is the code snippet used to s ...

What is the best way to continuously make an ajax request in Angular.js and terminate it depending on the response received?

I am looking for advice on how to optimize my controller in order to run a periodic ajax call every 15 seconds instead of just once. Additionally, I am wondering how I can stop the call when needed. myApp.controller('myCntrl', function($window,$ ...

Grails 3 - Resource Management Extension

Can anyone recommend a great Grails plugin for the latest version of Grails 3 (specifically working with 3.0.4)? I'm looking for something like this one () that allows me to create resource bundles for JS, CSS, and other dependencies. I think having ...

Migrate the JavaScript variable created with 'passport' to an Express router

In my quest for authentication, I created the essential passportAuth.js file: module.exports = function(passport, FacebookStrategy, config, mongoose, fbgraph){ passport.serializeUser(function(user,done){ //to make user reference available across pages ...

Select element's width decreases by 2 pixels following the application of width adjustment via jQuery

After browsing through numerous pages, I finally managed to adjust the width of my textbox and select element using jQuery 2.0. Snippet of Code from my Project: $(document).ready(function(){ $("#Text2").css('width','20 ...