Arranging an ng-repeat list in a dynamic order

I am currently working with AngularJS and focusing on reordering the ng-repeat list. The list represents online users who can receive messages at any time. When a user receives a message, I update the UI to display the most recent message beneath their name.

To achieve this, I am sorting the user list based on those who have received the most recent messages. Users who receive messages should be displayed at the top of the list.

Here is an excerpt of the code:

$scope.$watch('service.get.userList()', function (values) {

    var result = [];
    angular.forEach(values, function (value) {


        processChatService.registerObserverCallback('lastMessage', function () { // Triggered when the user receives a message
            $scope.$apply(function () {
                value.l = processChatService.get.lastMessage(value.u); // Retrieves the latest message
                value.time = processChatService.get.lastMessageTime(value.u); // Gets the timestamp
            });
        });
        value.l = processChatService.get.lastMessage(value.u); // Returns null if the user hasn't received a message
        value.time = processChatService.get.lastMessageTime(value.u);

        result.push(value);
    });
    $scope.users = result;
});

HTML:

<div ng-repeat="user in users | filter:search"> <a class="list-group-item" ng-click="click(user)" ng-href="">
                        <div class="row">
                            <div class="col-xs-2">
                                <div class="thumb-userlist-sm pull-left mr">
                                    <img class="img-circle"  ng-src="{{ user.p }}" alt="...">
                                </div>
                            </div>
                            <div class="col-xs-8">
                                <div class="message-sender">{{ user.n }}</div>
                                <div class="message-preview">{{user.l}}</div>
                            </div>
                            <div class="col-xs-2">
                                <div class="pull-right">{{user.time}}</div>
                            </div>
                        </div>
                    </a>

    <div class="row">
        <div class="col-xs-2"></div>
        <div class="col-xs-10">
            <div class="line-separator"></div>
        </div>
    </div>
</div>

Answer №1

To achieve the desired outcome, consider organizing the ng-repeat in the following manner:

<div ng-repeat="user in users  | filter:search | orderBy: 'time'">

This arrangement will sort the users based on the time attribute of each user. Additionally, you can invert the sorting sequence using -time.

For further details regarding the application of the orderBy filter, refer to the angular documentation.

Answer №2

To achieve this, we can utilize the orderBy function based on the specific requirement, which in your case is time.

<div ng-repeat="user in users  | filter:search | orderby:'time'"> <a class="list-group-item" ng-click="click(user)" ng-href="">
                        <div class="row">
                            <div class="col-xs-2">
                                <div class="thumb-userlist-sm pull-left mr">
                                    <img class="img-circle"  ng-src="{{ user.p }}" alt="...">
                                </div>
                            </div>
                            <div class="col-xs-8">
                                <div class="message-sender">{{ user.n }}</div>
                                <div class="message-preview">{{user.l}}</div>
                            </div>
                            <div class="col-xs-2">
                                <div class="pull-right">{{user.time}}</div>
                            </div>
                        </div>
                    </a>

    <div class="row">
        <div class="col-xs-2"></div>
        <div class="col-xs-10">
            <div class="line-separator"></div>
        </div>
    </div>
</div>

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 'disabled' property is not found in the 'MatButton' type, however, it is necessary in the 'CanDisable' type

Issue found in node_modules/@angular/material/core/option/optgroup.d.ts: Line 17: Class '_MatOptgroupBase' does not correctly implement interface 'CanDisable'. The property 'disabled' is missing in type '_MatOptgroupBas ...

Troubleshooting: AngularJS Http Post Method Failing to Execute

I am attempting to make an HTTP POST request to update my database using AngularJS. Although my code is not displaying any errors, the database is not being updated and I'm having trouble pinpointing the issue. Below is the code snippet: //topic-serv ...

Is it possible to invoke an AngularJs service by clicking a button?

Recently, I've been working on some AngularJS code involving a service and controller. angular.module('myModule', []).service("AttendanceService", function ($http) { this.getdata = function () { return $http({ ...

How can I check if the VPN is turned off in a React application?

import React from "react"; import { Offline, Online } from "react-detect-offline"; export default function DropDown() { return ( <> <Online>Only displayed when connected to the internet</Online> <Offline ...

Refreshing HTML Form upon Submit using JavaScript

I've been searching through various discussions without any luck, but I'm encountering an issue with a form that successfully submits data to a Google Sheet, yet the input fields retain their content after submission. Here is the code: <form ...

Trouble accessing state when React child calls parent method

Within my project, I am working with 3 components that are nested as follows: App->GameList->GameItem The App (parent) component has a method that is triggered by the onClick event within the GameItem (child) component Upon clicking the GameItem co ...

Looking for a method to substitute "test" with a different value

Showing a section of the menu using <li id="userInfo" role="presentation" data-toggle="tab" class="dropdown"> <a href="#" name="usernameMenu" class="dropdown-toggle" data-toggle="dropdown" role="button"> <span class="glyphicon glyph ...

Strategies for extracting data from a third-party website that utilizes JavaScript to set the value

Before, I would use jQuery to load external website content such as html or json. Sometimes, I even utilized a proxy PHP page in order to bypass strict origin policies on certain sites. However, I've encountered an issue with some websites. In the HT ...

What is the trick to getting an accordion to expand when hovering, rather than when clicking?

Can the accordion be set to expand when hovering instead of clicking? Also, how can a different action be triggered on click? LATEST I was specifically referring to using the jQuery UI accordion widget for this functionality. ...

Show a modal component from another component in Angular 2

As a newcomer to Angular, I'm working on a modal component that changes from hiding to showing when a button with (click) is clicked. The goal is to integrate this modal into my main component, allowing me to display the modal on top of the main conte ...

What is the method for displaying a div adjacent to a password input field?

I am attempting to display a password verification box next to an input field. The current logic is functioning properly, but the box containing all password requirements is not appearing in the correct position. Instead of being positioned adjacent to the ...

Navigating routes with regular expressions in Express

Recently, I've implemented the regex pattern /^\/(\d{5})$/ in my express route. However, an error has surfaced. The error message reads: SyntaxError: Invalid regular expression: /^\/^\/(?(?:([^\/]+?)){5})$\/?$/: Inval ...

Issues with BoxWidth configuration in ChartJS causing unexpected results

Check out my demo on JSFidle: https://jsfiddle.net/uniqueusername/example123/ In the chart, there is a noticeable pink box at the top. I'm trying to remove it. Some suggestions I found involved adding the following code: legend: { labels: { ...

What is the best way to attach information to a chart prior to the jquery dialog box appearing?

I am currently working on a web application that interacts with an Azure database. The goal is to create a graph based on user selections from a radio list and two inputted time parameters. The intention is to showcase this graph in a jQuery dialog box tha ...

Steps to establish the starting value as 'Concealed'

I stumbled upon this interesting example that demonstrates how to create expandable/collapsible text when clicked. My question is, how can I initially set the value to be hidden so that the paragraph starts off collapsed and expands only when clicked? He ...

compress a website to display advertisement

Here is a JSFiddle link I would like to share with you: I am currently working on squeezing the webpage to display an ad on the right side. http://jsfiddle.net/5o6ghf9d/1/ It works well on desktop browsers, but I am facing issues with iPad Safari/Chrome ...

Tips for transferring date values in an ajax request to a web application handler

I am currently working on plotting a graph between two dates using Google Charts. My goal is to send date values to the controller, which is implemented with webapp2. However, I am facing difficulties in figuring out how to send date values to the controll ...

Are `<text>` nodes unable to utilize ligature fonts in CSS/SVG?

Check out this JsFiddle demo: http://jsfiddle.net/d0t3yggb/ <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <div class="material-icons">add add add add</div> <svg width="100%" height="100% ...

Is there a way to display only the specific child div within the parent div using JavaScript without affecting the others?

   **** Sorry for the lengthy title **** Today I encountered a problem that I would like to discuss with all of you. When I click on a "COMMENT" button, instead of triggering JavaScript code to display a CHILD.div inside the corresponding ...

The error message "Uncaught ReferenceError: e is not defined" is popping up in my code when

As a beginner with React and Material-UI, I am encountering an error that I cannot seem to resolve. When I load a component using material-ui/data-grid, the data grid simply displays "An error occurred" in the app. However, when I load the component withou ...