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

Having trouble developing a custom jQuery tool for textareas

I am currently attempting to customize this script that mimics the Word 2007 minibar within a textarea. My approach involves encapsulating it in a plugin, but I am encountering an issue where it does not function properly with multiple textareas. If you w ...

Loading game resources in advance for future or immediate utilization

I'm currently developing a game UI that involves a large number of image files, totaling around 30MB in size. I've been caching these images to the disk using service workers, but some of them are quite large at 3MB each. Even when they are retri ...

Warning: The Unhandled Promise Rejection arises when an error is thrown within an asynchronous function without a try-catch block

Encountering the following issue in my Node-Express App UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error came about either by throwing inside an async function without a catch block, or rejecting a promise that was not hand ...

What is the best way to save the output of a middleware in express js so that it can be conveniently accessed by the rest of the

Currently, I am working with a middleware that returns an object. My goal is to save this object so that other parts of the application can utilize the data it contains. How can I achieve this? This snippet is from my app.js file: import { myMiddlewareFun ...

Adjust font size using jQuery to its maximum and minimum limits

My jQuery script enables me to adjust the font-size and line-height of my website's CSS. However, I want to restrict the increase size to three clicks and allow the decrease size only after the increase size link has been clicked - ensuring that the d ...

How can I prevent right-clicking with Ctrl+LeftMouseClick in Firefox on MacOS?

I'm looking to implement a shortcut using Ctrl+LeftMouseClick in my React project. It functions perfectly on Chrome on my Mac, but in Firefox the shortcut initiates a right mouse click (event.button = 2). I believe this may be due to MacOS's Rig ...

Dealing with React Native text overflowing beyond the screen width when using FlexWrap

I'm currently working on implementing a component in react native that consists of a row containing and components, but I'm struggling to achieve the desired outcome. Here's my current code: <View style={{ flexDirection: ...

What is the best way to retrieve the height of the parent element in my specific situation

I am facing an issue in my directive where I need to access the height of the parent element. Here is a snippet of my code: (function(window, angular) { var app = angular.module('myApp'); app.directive('testElem', [ fu ...

The Requirejs Optimizer is failing to compile

Struggling with getting the optimization tool to work while using requirejs. My aim is simple: optimize my javascript files into one script file with all dependencies included. All my files reside in the js/ folder, including a subfolder named vendors/ M ...

The console log is displaying 'undefined' when trying to access Node.js fs

Recently, I was engrossed in developing a Next.js blog. After completing the frontend, I shifted my focus to building the backend using Next.js. ./pages/api I created a new file: ./pages/api/blogs.js To test my backend functionalities, I generated some J ...

Make the div disappear after a specified time

Does anyone know of a code snippet that can make a couple of div elements fade out after a specific time period? Currently, I have the following example: <div id="CoverPop-cover" class="splash"> <div id="CoverPop-content" class="splash-center"> ...

What is the best way to transmit a collection of JSON documents from the server?

Need help with vue.js code. It's not working as intended, any suggestions? Below is the code snippet: mounted(){ fetch('/', { method: 'POST', // *GET, POST, PUT, DELETE, etc. mode: 'cors', // no-cors, *cors, ...

Creating dynamic child components in Vue.js version 2

I am currently developing a facet search system using VueJS. The concept is fairly straightforward: Within a FilterGroup component lies the overarching filter logic. This component allows for several child components, such as AttributeXYZFilter, to provid ...

Issues with Jquery keyup on Android devices - unable to detect keyup

I have not tested this code on an iPhone, but I am certain (tested) that it does not work on Android mobile devices: $('#search').live('keyup',function(key){ if(key.which == 13){ /*ANIMATE SEARCH*/ _k ...

Retrieve the properties from within a closure function in a functional component

I have developed a simple React application using create-react-app. The app consists of a single component that takes in a value and an onClick callback. When the callback is triggered, the value increments. import React, { useState } from 'react&apos ...

Database Submission of Newsletter Information

I recently grabbed the following code snippet from a YouTube tutorial (shoutout to pbj746). Everything appears to be functioning correctly except for one crucial issue - the submitted data isn't showing up in the database! I've thoroughly checked ...

Using constant values in Angular JS services without altering them

I'm a beginner with AngularJS and I'd like to establish a global variable that can be accessed across different services as the web service URL. Here's how I've set up my app.js (module): var app; (function () { app = angular.modu ...

Choose the span element within every other td that is not enclosed by an anchor tag

The table structure I am working with is as follows: <tr> <td> <a> <span> some content </span> </a> </td> <!-- td having straight span --> <td> <span> ...

The functionality of the controls is not functioning properly when attempting to play a video after clicking on an image in HTML5

While working with two HTML5 videos, I encountered an issue with the play/pause functionality. Despite writing Javascript code to control this, clicking on one video's poster sometimes results in the other video playing instead. This inconsistency is ...

Create a smooth scrolling effect for a div with a fixed position

Having trouble scrolling a fixed position div on the page? Are you using this jquery script: $('html, body').animate({ scrollTop: $(".example").offset().top }, 750); I had to set the body overflow property to hidden for another issue. The ...