Arranging items by specific criteria in ng-repeat for a personalized sorting experience

Within my controller, I have an object named $scope.addresscards. The JavaScript code is provided below:

var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
  $scope.addresscards = {
      "work_address": {
          "location":"workLoc",
          "address": "workAddr",
          "flat_no": "worknumber",
          "landmark": "workLandmark"
      },
      "random1_address": {
          "location":"someLoc",
          "address": "SomeAddr",
          "flat_no": "Somenumber",
          "landmark": "someLandmark"
      },
      "home_address": {
          "location":"homeLoc",
          "address": "homeAddr",
          "flat_no": "homenumber",
          "landmark": "homeLandmark"
      },
      "random2_address": {
          "location":"someLoc2",
          "address": "SomeAddr2",
          "flat_no": "Somenumber2",
          "landmark": "someLandmark2"
      }
  };
}

To display the addresses using ng-repeat, I've created the following HTML structure:

<div ng-controller="MyCtrl">
  <ul ng-repeat="(addressKey,addressVal) in addresscards">
     <li>{{addressKey}} has :: {{addressVal.location}},{{addressVal.address}}, {{addressVal.location}}, {{addressVal.address}}</li>
  </ul>
</div>

The current output I'm getting is as follows:

home_address has :: homeLoc, homeAddr, homeLoc, homeAddr
random1_address has :: someLoc, SomeAddr, someLoc, SomeAddr
random2_address has :: someLoc2, SomeAddr2, someLoc2, SomeAddr2
work_address has :: workLoc, workAddr, workLoc, workAddr

However, my desired output format should prioritize displaying 'home_address' first, followed by 'work_address', and then alphabetically arrange the remaining objects.

Expected output:

home_address has :: homeLoc, homeAddr, homeLoc, homeAddr
work_address has :: workLoc, workAddr, workLoc, workAddr
random1_address has :: someLoc, SomeAddr, someLoc, SomeAddr
random2_address has :: someLoc2, SomeAddr2, someLoc2, SomeAddr2

Despite attempting to use orderBy, it doesn't function as intended for objects. How can I accomplish this sorting?

Answer №1

To enhance your address objects, you have the option to include a new property

$scope.addresscards = {
      "work_address": {
          "location":"workLoc",
          "address": "workAddr",
          "flat_no": "worknumber",
          "landmark": "workLandmark",
          "sort" : "2"
      },
      "random1_address": {
          "location":"someLoc",
          "address": "SomeAddr",
          "flat_no": "Somenumber",
          "landmark": "someLandmark"
      },
      "home_address": {
          "location":"homeLoc",
          "address": "homeAddr",
          "flat_no": "homenumber",
          "landmark": "homeLandmark",
          "sort" : "1"
      },
      "random2_address": {
          "location":"someLoc2",
          "address": "SomeAddr2",
          "flat_no": "Somenumber2",
          "landmark": "someLandmark2"
      }
  };

When using ng-repeat, consider ordering by multiple fields such as sort for priority display of home and work addresses, followed by alphabetically sorting by address key.

<ul ng-repeat="(addressKey,addressVal) in addresscards | orderBy:['sort','addressKey']">
     <li>{{addressKey}} has :: {{addressVal.location}},{{addressVal.address}}, {{addressVal.location}}, {{addressVal.address}}</li>
  </ul>

Alternatively, within your controller, arrange all other addresses first and then add home and work addresses at the beginning of the list.

Plunker

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 number of subscribers grows every time $rootscope.$on is used

I currently have an Angular controller that is quite simple: angular.controller('appCtrl', function ($scope, $rootScope) { $rootscope.$on('channel.message', function () { // do something here } }); In addition, I have a ...

Difficulty encountered with Mongoose/MongoDb FindOneAndUpdate functionality

My goal is to update a specific location only if it has a status of 0 or 2, but not if the status is 1. There is only one instance of this location in my database. Property.findOneAndUpdate({ status: 0, location: req.body.update.location }, req.body.updat ...

JavaScript file encountering a problem with its global variables

What is causing the alert("2") to pop up first instead of it being second? Why am I encountering difficulty creating global variables c and ctx? Is there a way for me to successfully create these two global variables in order to utilize ...

Method for setting a checkbox as checked based on whether its value can be found in an array

I currently have the following input fields: <div id="my"> <input type="checkbox" value="1" name="names[]"> <input type="checkbox" value="2" name="names[]"> <input type="checkbox" value="3" name="names[]"> <input t ...

Error encountered while attempting to save a Mongoose post on Heroku, although it is successful

My aim is to post to my MongoDB Atlas database using node, express, mongoose, and Heroku. While a Postman POST request with Raw JSON body: { "title": "heroku post", "description": "post me plsssss" } works f ...

Display/Conceal a div using CSS in React JS/Redux

I've been working on a CSS toggle for a div with className toggling. My approach involves using redux to manage the boolean state. Using the redux chrome extension, I can see that the state is indeed changing but the div remains invisible. If you have ...

The process of transferring information from a JSON API to TypeScript models

When working with my JSON API in my services, I need to pass the data to my models. What is the most efficient way to accomplish this task? Currently, I am following this process: import { Attachment } from '.'; export class Contact { id: nu ...

Executing JavaScript when a specific portion of a webpage loads in the presence of AJAX: A guide

As I tackle a project that involves loading elements via AJAX within a CMS-type software, I find myself restricted in accessing the AJAX code and its callbacks. One specific challenge I face is running my function only when a certain part of the page is l ...

undefined event typescript this reactjs

I have come across the following TypeScript-written component. The type definitions are from definitelytyped.org. I have bound the onWheel event to a function, but every time it is triggered, this becomes undefined. So, how can I access the referenced el ...

Avoid running old JavaScript code when using turbolinks in conjunction with highcharts library, specifically LazyHighCharts

Utilizing turbolinks 5 and rails version 5, along with the latest Highcharts has been causing me some issues. T LazyHighCharts offers a solution for Turbolinks 5 by encapsulating chart building javascript within (function() { document.addEventListe ...

Having trouble with the dropdown feature on AngularJs?

Encountering an issue while trying to display the dropdown list. Upon inspecting in Chrome, it seems like the data is loading correctly but when clicked, the dropdown menu does not show up. The data is fetched from the BooksController and all options are ...

What is the best way to input an HTML element into AngularJS code?

I am looking to integrate the html element into my angularjs code. Within my HTML, I have elements such as data-form-selector='#linechart_general_form' and data-url="{% url 'horizon:admin:metering:samples'%}" that I need to access withi ...

Tips for executing nodemon and forever in the background

Good morning! Having an issue with my node.js server running in the background. I came across this helpful thread on Stack Overflow which suggested using Forever + Nodemon together I like the concept, however, when I implement it as shown here: forever ...

Validating forms in ReactJS

I have developed a basic form validation feature for React. The inspiration for this project came from the following source: When I try to submit the form, input errors arise within the isValid function. I am seeking assistance in resolving this issue. A ...

The functionality of the Angular directive ngIf is not meeting the desired outcome

We are currently working on transferring data from one component to another using the approach outlined below. We want to display an error message when there is no data available. <div *ngIf="showGlobalError"> <h6>The reporting project d ...

Tips for transferring information from Django to React without relying on a database

Currently, I am in the process of developing a dashboard application using Django and React. The data for the user is being pulled from the Dynamics CRM API. To accomplish this, I have implemented a Python function that retrieves all necessary informatio ...

Express validator in NodeJS is commonly used for error validation, specifically with the

I'm looking for assistance with express-validator and connect-flash in a basic NodeJS application I am working on. In my usercontroller module.exports.post, I have req.flash('error', errors) which successfully flashes the error messages usi ...

Keep the Bootstrap modal open while the JavaScript validation is running, and redirect the form action if the validation is successful

When trying to execute the submit event from a form, my code is supposed to keep the modal open if validation fails. However, for some reason, this functionality is not working as expected. var myForm = document.updteform; var condition = true; if ...

Acquire data from an array of objects using JavaScript

I've written some code where I'm attempting to display certain values in HTML. Specifically, I am looking to extract the values from the "current" object: ("dt":1643884851, "temp":8.11, "description":"few clouds", and "icon":"02d") In addition, ...

Meteor: How to upload an image file by utilizing the FileReader on the client side and Npm requiring "fs" on the server side

I am facing difficulties trying to upload an image file to my public/ directory using a standard <input type="file"> element. This is the code snippet causing issues: "change .logoBusinessBig-upload":function(event, template){ va ...