Ordering ng-repeat in AngularJS using a separate arrayDiscover how to easily order your

Imagine I have an array containing keys in a specific order

orderedItems=["apple","banana","orange];

and there is a JSON object that I want to display using ng-repeat but following the sequence specified in the array:

{"fruits":
    {
    "apple":{
        "color":"red",
        "taste":"sweet"
        },
    "banana":{
        "color":"yellow",
        "taste":"creamy"
        }, 
    "orange":{
        "color":"orange",
        "taste":"citrusy"
        }
    }
}

How can I create a filter so that ng-repeat lists the fruits in the exact order as they are mentioned in the array?

<li ng-repeat="item in fruits | customOrder"></li>

Answer №1

If you want to create a custom filter, follow these steps:

View the example on Plunker: http://plnkr.co/edit/fiuuGoGZK7tM5oefKQlS

Here is the code for index.html:

<!DOCTYPE html>
<html ng-app="plunker">

<head>
    <meta charset="utf-8" />
    <title>Filter Example</title>
    <link rel="stylesheet" href="style.css" />
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3e5f50594b525f4c10544d7e0f100c1046">[email protected]</a>" src="http://code.angularjs.org/1.2.15/angular.js" data-semver="1.2.15"></script>
    <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
<li ng-repeat="person in people|orderNames:orderedNames track by $index">{{person.hair}}</li>
</body>

</html>

And here is the content of app.js:

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

app.controller('MainCtrl', function($scope) {
    $scope.people={
        bob:{
            hair:"brown",
            eyes:"blue",
            height:"tall"
        },
        sarah:{
            hair:"blonde",
            eyes:"blue",
            height:"short"
        },
        mike:{
            hair:"red",
            eyes:"blue",
            height:"tall"
        }
    };
    $scope.orderedNames=["mike","bob","sarah"];

});

app.filter("orderNames",function(){
    return function(input,sortBy) {
        var ordered = [];
        for (var key in sortBy) {
            ordered.push(input[sortBy[key]]);
        }

        return ordered;
    };
});

Answer №2

Here's a suggestion you might want to consider

<li ng-repeat="name in orderNames">
    {{people[name]}}
</li>

Answer №3

Using an array as a reference:

Check out this link for more information on arrays

    $scope.persons = {
   bob:{
     name:'bob'
   },
   mike:{
     name: 'mike'
   },
   sarah: {
     name: 'sarah'
   }
 };

 $scope.orderedNames = [$scope.persons.mike, $scope.persons.bob, $scope.persons.sarah];

HTML :

<ul ng-repeat="person in orderedNames">
         <li>{{ person.name }}</li>
       </ul>

Answer №4

when you need to iterate over an array in a different order specified by another array, follow these steps:

Firstly, set up the following code snippet in your controller:

$scope.sortOrder = [1,2,3,4] //or any desired sorting order

Next, in your template, use the following syntax:

| orderByCustom:sortOrder:true/false

The true/false flag determines whether items not present in the sorting array will be displayed at the end or excluded altogether.

Don't forget to implement the custom filter as shown below:

var app = angular.module("app", []).filter("orderByCustom", function () {
            return function (input, sortOrder, includeOrphans) {
                //sorts by specified array and places unsorted items at the end if not in sorting array
                if (!angular.isDefined(input)) { return; }
                var ordered = [];
                var remaining = _.cloneDeep(input);
                angular.forEach(sortOrder, function (orderItem) {
                    if (angular.isDefined(input[orderItem])) {
                        ordered.push(input[orderItem]);
                        delete (remaining[orderItem]);
                    }
                });
                if (includeOrphans) {
                    angular.forEach(remaining, function (remainingItem, key) {
                        ordered.push(input[key]);
                    });
                }
                return ordered;
            };
        });

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

Leveraging AngularJS for a Windows store app

After attempting to integrate AngularJS into my Windows store application, I came across a few recommended solutions: Unfortunately, these solutions did not work as expected. While I didn't encounter the Unable to add dynamic content error, AngularJS ...

Should we integrate a MongoDB database calculation app with a POST Controller in sails.js?

The primary function of the application interface is to provide variables that have been initially posted by the client, as well as any subsequent database calculations carried out in real time by a specialized engine. Is it possible to integrate this eng ...

Creating a new JavaScript object using a Constructor function in Typescript/Angular

Struggling with instantiating an object from an external javascript library in Angular/Typescript development. The constructor function in the javascript library is... var amf = { some declarations etc } amf.Client = function(destination, endpoint, time ...

Incorporating Bootstrap JS into Next.js

Currently, I am in the process of learning next.js and experimenting with incorporating Bootstrap into my projects. To begin, I initiated a new project using npx create-next-app@latest my-app, utilizing the newly created "app" directory structure. Follow ...

Upcoming verification with JSON Web Token

I am looking to incorporate JWT auth into my Next app. Currently, I have mapped out the flow as such: User enters email and password to log in Server responds with status 200 and a jwt access token in httpOnly cookies My main dilemma lies in deciding on ...

Looking to prevent printing and saving a webpage directly from the file menu using JQUERY or JavaScript

I am in need of assistance to find a code that can disable the ability to print and save a webpage using JQUERY or JAVASCRIPT ...

Unresolved Issue: Jquery Modal Fails to Activate on Subsequent Click for Ajax-

When I make an Ajax call, I load HTML into a div. This HTML content contains a jQuery modal that opens when clicked. However, on the first click, the modal opens correctly. On subsequent clicks, I receive the following error in the console: Uncaught Type ...

What is the method to close the picker when using type="datetime-local"?

Currently, I am utilizing Vue with the "datetime-local" type for input. While I can successfully select the date and time, my goal is to have the picker close automatically after a selection has been made. I've experimented with adding an onchange ev ...

How can I utilize customToJSON in Sails 1.0 within an Action2 function?

Currently, I am facing an issue with my user model that requires the implementation of a customToJSON method to remove the password field from the returned JSON object. Everything works fine when I include "responseType" in the "exits" with a value of "jso ...

What is the best way to ensure that the HTML page is only shown once all data from three JSON files has been fully

I have successfully parsed data from three different JSON files using the code below. //factory app.factory('myapp', ['$http', function($http) { function getLists() { var tab = [&a ...

Sending data from Ajax to PHP

I've gone through all the previous examples without success, and now I am facing a simple php question. You can find the example here. My goal is to click on a table and have the options displayed as follows: When I explicitly declare the table name ...

Customize nestjs/crud response

For this particular project, I am utilizing the Nest framework along with the nestjs/crud library. Unfortunately, I have encountered an issue where I am unable to override the createOneBase function in order to return a personalized response for a person e ...

Waiting for state changes in React by using the UseState Hook

I am currently working on a function that manages video playback when clicked, and I need to set consecutive states using the useState hook. However, I want to ensure that the first state is completed before moving on to the next setState without relying ...

Is there a way to retrieve data from three different Bookshelf.js models in a single query?

Three tables are in my database: User, UserDrink, and VenueDrink Here is a preview of the sample data: User id | name | gender | -------------------- 1 | John | male | 2 | Jane | female | UserDrink id | count | user_id | venue_drink_id 1 | 3 | ...

JavaScript in IE/Edge may not run correctly if it is loaded from the cache

I am facing a peculiar problem with Internet Explorer (IE) and Edge. Upon initially loading a page, everything functions perfectly fine. However, if I navigate away from the page to another page on the same website, JavaScript errors start showing up on th ...

Generate a unique promise with custom functionality using JavaScript bindings in Selenium WebDriver

Is there a specific way to generate a personalized promise within a Selenium WebDriver environment using Node.js? Typically, in a Node.js application, I would produce a promise that encapsulates all of my asynchronous calls like so: return new Promise(fu ...

Receive the deleted entry upon clicking the thead | Error发

Is there a way to permanently delete a row in a datatable? If I delete all the rows, I would like the datatable to display the default message of "No data available". I have attempted some POST requests : But with no success. DataTables remove row butto ...

Insert HTML content into an iframe with a callback function

We are receiving information from the backend server and need to transfer it to an iframe. In order to accurately set the height of the iframe to match the content, we must wait for the content to be loaded into the iframe. However, this process may not ha ...

Setting environment variables using the node command is successful on Linux and macOS platforms, however, it may not function properly

When I clone a project using git, I encounter issues running npm run build on Windows. The command works fine on Mac and Linux: "build": "API=https://dev-api.myexample.com/v1.0 babel-node build.js", An error message is displayed: 'API' is no ...

Function cannot be called upon directive initialization

I'm currently developing a custom directive in AngularJS and I am facing an issue with calling a function upon loading my directive. My attempt to call the function within the link function resulted in an error message saying TypeError: scope.setCurr ...