Sorting objects in Angular using ng-options

I am working with an object that has the following structure:

{
   3019: 'Javascript',
   3046: 'Css'
}

After that, I display this object in a select element like this:

<select
    ng-model="langChoosed"
    ng-options="key as value for (key, value) in progLanguages"
></select>

I am trying to figure out how to sort the items inside the select. The orderBy filter only seems to work on arrays. Is there a way to make it work with objects?

Answer №1

Unfortunately, you cannot apply an order by function to a plain object. However, you have the option to create a method in the controller that will convert the object to an array.

Check out this demonstration:

var app = angular.module('todoApp', []);

app.controller("dobController", ["$scope",
  function($scope) {
    $scope.progLanguages = {
      3019: 'Javascript',
      3046: 'Css'
    };
    $scope.templatesAry = function() {
      var ary = [];
      angular.forEach($scope.progLanguages, function(val, key) {
        ary.push({
          id: key,
          lang: val
        });
      });
      return ary;
    };
  }

]);
<!DOCTYPE html>
<html ng-app="todoApp">

<head>
  <title>To Do List</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>

</head>


<body ng-controller="dobController">
  <select class="form-control" id="selection" ng-model="currentSelected" ng-options="selection.id as selection.lang for selection in templatesAry()  | orderBy:'lang'"></select>
</body>

</html>

Answer №2

Do note that object keys are inherently unordered, making it impossible to sort them directly. One workaround is to convert your object into an array, sort it accordingly, and then proceed with its usage:

var sortedArrayOfObjects = Object.keys($scope.languages).map(function(key) {
    var obj = {};
    obj["key"] = key;
    obj["value"] = $scope.languages[key];
    
    return obj;
});

// Sort the array
sortedArrayOfObjects.sort(function(a, b) {
    return +a.key - +b.key; // Ensure integer casting for proper comparison
});

// Assign the sorted array
$scope.sortedLanguages = sortedArrayOfObjects;

Now you can make use of it in your code:

<select
ng-model="selectedLanguage"
ng-options="item.key as item.value for item in sortedLanguages"></select>

Answer №3

How about this solution for you?

  var myObject = {
      3046:'CSS',
    3019:'JavaScript'
  };
  var allKeys = [];

angular.forEach(myObject, function(val,key){
    allKeys.push(key);
});

allKeys.sort();

$scope.myNewObject={};
angular.forEach(allKeys, function(k){
    $scope.myNewObject[k]=myObject[k];
});

Here is your HTML code:

<select
    ng-model="selectedLanguage"
    ng-options="k as val for (k, val) in myNewObject"
></select>

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

Tips and tricks for bypassing the annoying "save as" popup while downloading files remotely using SauceLabs

Running a protractor spec from a Jenkins job, connecting to SauceLabs to click a button for downloading a PDF file, and verifying the successful download. Struggling to prevent the chrome browser from displaying a "Save As" prompt when using an absolute pa ...

NPM encountered an issue that prevented it from scanning directories due to a permission denial with the error code E

Whenever I type "npm run build:prod" build:prod npm run build -- --configuration production --aot --optimization=false I encounter the following error: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="82e4e3ece1fbafece3 ...

JavaScript is utilized to update HTML content through an Ajax request, but unfortunately, the styling is

Apologies for the unconventional title, I am currently in the process of creating a website. When the page is initially loaded, I call upon two scripts within the 'head' tag to create an attractive dynamic button effect. <script src="https:// ...

When I refresh the page in Angular2, the router parameters do not get loaded again

When loading my application on routers without parameters, everything is normal. However, when trying to use a router with params, the application fails to load. For example: localhost:3000/usersid/:id The code for the router is as follows: const appRou ...

Rearranging components in React does not automatically prompt a re-render of the page

I'm currently working on a project to display the update status of my Heroku apps. The issue I encountered was that the parent component (Herokus) was determining the order, but I wanted them sorted based on their update dates starting from the most r ...

Selecting a main node using the key value

Is there a way to select the root node of a d3.hierarchy based on a specific JSON key value? For instance, instead of having "A1" as the root node in the given JSON object, can we make "B1" the root node by referencing its name value? { "name": "A1", ...

Presenting XML data on a webpage using AJAX technology

I am currently working on setting up a web radio station with a program that allows streaming (jazler) to send xml files via ftp to a web server to automatically update information such as the current song playing and previous songs. The code for NowOnAir ...

Issue with AngularJS form not submitting dataAngularJS form not processing values

I've created a form with two select elements and two buttons: <form> <select class="browser-default" ng-model="TAV"> <option value="11">11</option> <option value="12">12</option> ...

Is it no longer necessary to bind functions in React Component Classes?

Recently, I observed that when defining normal class component functions in React, there is no longer a need to bind them inside the class constructor. This means that even without using ES6 public class field syntax, you can simply pass these functions to ...

Utilize AngularJS to sort through a JSON array and display the information in dual tables based on the array item

Recently, I came across some JSON data that looks like this: { "id": 2, "itemList": [ { "id": 7, "name": "xx", "extraInfo": "45", "tax": 21.00, "price": null, "oneTimeItem": false, "fkIdUserItem": 2, ...

The error message "TypeError: Router.use() expects a middleware function, but received a [type of function]" is a common occurrence in FeathersJS

Struggling to bind a method to my /userAuthenticationInfo route, I've made several adjustments in my code based on other posts related to this issue but still unable to make it work. I am using feathersJS's express implementation, and even with e ...

What is the best way to reset the scroll position of a div when you stop hovering over a link?

Can anyone help me figure out how to reset the scroll wheel when hovering over dropdown menu items? I've tried multiple solutions found online, but none seem to be working for me. If you have any ideas on how to accomplish this, please let me know! f ...

Monitoring a variable inside a service using AngularJS

I am currently in the process of developing a web application using AngularJS. My application consists of a primary view (Index), a child view (Dashboard), and a grandchild view (Raiding The Rails). http://localhost:4000/#/dashboard/raiding-the-rails/1 ...

Tips for expanding frisby.js by adding new "expect" functionalities?

Looking to enhance the Frisby.js module with custom expect methods without altering the source code. These extensions are tailored for my REST API to streamline common tests into a single method. An issue arises as the Frisby.js module exports its methods ...

Angular 2: trigger a function upon the element becoming visible on the screen

How can I efficiently trigger a function in Angular 2 when an element becomes visible on the screen while maintaining good performance? Here's the scenario: I have a loop, and I want to execute a controller function when a specific element comes into ...

Implement a code to apply to an image that is loaded dynamically

I have a situation on a page where an image is loaded via ajax within a wrapping div. I need to execute some code as soon as that image is loaded. Unfortunately, I am unable to modify the ajax call, which means using on('success') directly on the ...

Having trouble with AngularJS and NodeJS routing integration?

After deciding to dive into the world of application development using the MEAN Stack, I encountered a major roadblock. For the past hour, I've been struggling to set up a basic route, only to face failure at every turn. Whenever I try to access my ...

What is the most efficient method for managing window properties and child components in React/Redux?

My <Layout> component loads different child components based on the page. Some of these children may have tabs, while others may not. This variation in content affects how scrolling should work and consequently influences the structure of the scroll ...

Iterate through an array, mapping the values and then returning a

Look at the code provided: const { aForm, bForm, eForm, qForm, } = this.form; return ( aForm.isEditing || bForm.isEditing || eForm.isEditing || qForm.isEditing ); Can we optimize this in a different ...

Can a JavaScript function spontaneously run without being called upon?

<a onclick="determineCountry(data)" class="installbtn">Install</a> My goal is to have the user redirected to one of three sites based on their location when they click the button above. However, there seems to be an issue with the script below ...