Adding a div to the preceding div based on matching IDs in AngularJS

Here is a representation of my layout in HTML:

<div ng-repeat="message in messages">
        <div ng-class="{'messages messages--sent': userId == message.id,         
            'messages messages--received': userId != message.id}">
                <div class="message">
                    {{message.content}}
                </div>
        </div>
    </div>
    

This is how the messages array is structured:

$scope.messages = [
        {
            "id":"Michael",
            "content":"Hey"
        },
        {
            "id":"Rich",
            "content":"Yow"
        },
        {
            "id":"Rich",
            "content":"How are you"
        },
        {
            "id":"Michael",
            "content":"Im okay"
        },
        {
            "id":"Michael",
            "content":"Im missed you!"
        },
    ];
    

This is the desired layout I'm aiming for

The previous layout is styled with the following CSS code:

.messages--received .message:first-child {
      border-top-left-radius: 50px;
    }

    // More CSS styling...

    .messages--sent .message:last-child {
        border-bottom-right-radius: 50px;
        margin-bottom: 10px;
    }
    

However, this is the issue that arises

The problem lies in the creation of a new div during each loop of ng-repeat, which I do not want. I aim to append the next {{message.content}} to the previously created div if their {{message.id}} matches.

If they do not match, a new div should be created as usual. Your assistance on this matter would be greatly appreciated. Thank you :)

Note: I prefer not to filter and group everything as I have tried before but faced misunderstandings. Hence, I have provided images this time to facilitate better comprehension. THANK YOU ^_^

Answer №1

The method provided may not be the most efficient way to handle this situation, but here is how it can be done:

<div ng-repeat="message in messages" ng-if="message.id != messages[$index - 1].id" style="border:1px solid red">
    <div >
            <div class="message">
                {{message.content}} - {{$index}}
            </div>
    </div>
  <hr>
    <div  
        ng-repeat="nextMessage in messages | startFrom : $parent.$index + 1"
         ng-if="nextMessage.id == messages[$parent.$index].id && ($index == 0 || nextMessage.id == messages[$index-1].id)" style="border:1px solid blue"
        >
            <div class="message">
                {{nextMessage.content}} - {{$index}}
            </div>
    </div>
</div>

You can also use an ng-repeat start index filter from:

app.filter('startFrom', function() {
    return function(input, start) {
        if(input) {
            start = +start; //parse to int
            return input.slice(start);
        }
        return [];
    }
});

I have added two ng-if conditions. One on the ng-repeat to skip iterations with matching ids from the previous one, and another inside to display subsequent items with matching ids. The nested ng-repeat adds each message with the same id until a different id is encountered.

You could integrate the first inner div within the ng-repeat as well, but for now, I have kept it separate.

Here is a fiddle without the CSS part, showcasing grouped messages highlighted in red: https://codepen.io/neptune01/pen/Qvzzed

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 could be causing my carousel slider images to not adapt to different screen sizes?

I recently added a carousel slider to my website, and while it looks great on larger screens like desktops and laptops, I noticed that the images are not scaling properly when viewed on smaller screen widths. This has resulted in non-responsiveness which i ...

I am attempting to arrange variables based on the key of the json nested within another json

It's a bit challenging to condense my goal into one question, but I'll try my best to clarify. I currently have a JSON array that represents various HTML slider elements categorized within 3 control panes: Basic, Interface, and Advanced. Each pa ...

Is there a way to adjust the padding temporarily?

Important Note: Despite the misleading title of my question, it doesn't accurately reflect my actual query (sort of). Below is the code snippet in question: .one{ background-color: gray; } .two{ padding: 20px; } <div class = "one"> < ...

Tips for implementing JS function in Angular for a Collapsible Sidebar in your component.ts file

I am attempting to collapse a pre-existing Sidebar within an Angular project. The Sidebar is currently set up in the app.component.html file, but I want to transform it into its own component. My goal is to incorporate the following JS function into the s ...

Managing a JSON request from an AJAX form using PHP - the ultimate guide!

I'm encountering some issues with my PHP handler. Here is the code snippet for my handler: <?php // Creating headers $headers = array( 'accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8&a ...

Could you explain the purpose of the usage section in a CodeMirror 6 language pack?

When you visit (for example) https://github.com/exercism/codemirror-lang-elixir?tab=readme-ov-file, you will see the following code snippet: import { StreamLanguage } from '@codemirror/language' import { elixir } from 'codemirror-lang-elixir ...

Enhancing the performance of jquery selection speed

I am currently working on a code that manipulates the HTML code of an asp.net treeview. Since this code runs frequently, I need to ensure that it executes with maximum speed. I am interested in expanding my knowledge on jQuery selectors and optimizing th ...

What is the best way to transfer data entered into a textbox through an onclick Alert event into a database?

UI https://i.stack.imgur.com/c2cqo.png Here is the PHP code I have been struggling with. It is meant to save input data into a database, but I can't seem to get it right: if (isset($_POST['rjctrsn-data']) && !empty($_POST['rjc ...

Oops! The provided value for the argument "value" is not a valid query constraint. Firestore does not allow the use of "undefined" as a value

I encountered an error while exporting modules from file A and importing them into file B. When running file B, the error related to Firebase Cloud Firestore is displayed. const getMailEvents = (startTime, endTime) => { serverRef = db.collection("Ma ...

Issues with login validation in HTML when utilizing JSON and PHP

While creating a login form in HTML using JSON and PHP, I encountered an issue where the if statements in the success function were not working properly. However, the beforeSend and error functions are functioning as expected. Can someone assist me in iden ...

How can I transmit a pong frame using WebSocket in javascript/NodeJS?

I am struggling to locate a proper example demonstrating how to send a PONG response using javascript/NodeJS within the context of a WebSocket connection (back to a server that requests it after sending a PING request). Can anyone provide guidance on thi ...

Top method for showcasing animated images (HTML/CSS/JS)

For my website, I want to create an engaging animation showing a coin being flipped multiple times in the air before landing on a specific side. After the animation finishes, I would like it to transform into a static image of the final result. I've ...

What is the best way to leverage command line arguments with AngularJS Protractor?

Currently, I am utilizing Protractor for executing extensive end-to-end tests. Instead of storing login credentials in a spec file, I am keen on passing them through the command line. Upon stumbling across a post showcasing the usage of process.argv.forEac ...

Issues with aligning div elements centrally

I have a dilemma with aligning two divs on my webpage. I am trying to position the second div in such a way that it is centered between the first div and the end of the page, like this: | | | | | | | | | | | | | | div1 | ...

Interactive elements embedded within an image - digital board game

I'm currently working on integrating a board game into React, and I am facing some difficulties in figuring out how to translate the board squares shown in the image into data. Is there a method through which I can assign unique IDs to each square di ...

Retrieving an element by its id in Angular 2

Hi there, I'm having some trouble with a code snippet: document.getElementById('loginInput').value = '123'; When trying to compile the code, I keep getting this error message: "Property value does not exist on type HTMLElement ...

Mongoose and MongoDB in Node.js fail to deliver results for Geospatial Box query

I am struggling to execute a Geo Box query using Mongoose and not getting any results. Here is a simplified test case I have put together: var mongoose = require('mongoose'); // Schema definition var locationSchema = mongoose.Schema({ useri ...

Challenges encountered when using node.js to write binary data

I've been attempting to write the binary body of a request to a file, but I'm encountering some issues. Although the file is successfully created on the server, I'm unable to open it and am receiving a 'Fatal error: Not a png' mess ...

Guide to transferring text to clipboard using PHP and JS

Forgive me if this sounds a bit silly. I've been trying to figure this out for a while now, and it seems like the only solution I found involves clicking some sort of button. I have a form that generates license keys, and after generating one, I wan ...

Implementing AJAX to dynamically update information based on user's selection from a dropdown

I need to dynamically adjust the opacity of my graph bars without requiring the user to manually refresh the page. I'm considering using AJAX for this purpose. How can I implement this functionality? const opacitySlider = document.getEle ...