Tips for implementing orderBy and filter in ng-repeat when working with an object instead of an array

I am facing a data structure that looks like this:

$scope.people = {
        "ID123": {
            name_de: "Andre",
            name_en: "Anrew",
            age: 30,
            description: "He is the father of xyz and . . .",

             . . .

        },
        "IDabc": {
            name_de: "Markus",
            name_en: "Mark",
            age: 20,

             . . .
        },
        "IDxyz": {
            name_de: "Isaak",
            name_en: "Isaac",
            age: 23,

             . . .
        }

    . . .

}

and I have an input/ng-repeat:

<input ng-model="query" placeholder="Search . . .">
<ul>
    <li ng-repeat="person in people | orderBy:'name_de' | filter:query"> Some output here . . . </li>
</ul>

The question now is how can I effectively order and filter this data?

I previously managed with an Array of persons, but I require the unique "ID's" which makes using objects necessary!?

Additionally, I am searching for a method to filter the object based on multiple properties, such as name_de AND name_en (so it will display ID123 if the search term is Andre or Andrew) WHILE disregarding the "description" property (initially the problem was that the filter checked all properties)

Answer №1

If you're looking to enhance your Angular skills, consider exploring the toArrayFilter module. You can find more information about it here.

For a hands-on experience, check out this sample demo of how to use the filter here:

angular.module('angular-toArrayFilter', [])

.filter('toArray', function () {
  return function (obj, addKey) {
    if (!(obj instanceof Object)) {
      return obj;
    }

    if ( addKey === false ) {
      return Object.values(obj);
    } else {
      return Object.keys(obj).map(function (key) {
        return Object.defineProperty(obj[key], '$key', { enumerable: false, value: key});
      });
    }
  };
});

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

app.controller('firstCtrl', function($scope){

  $scope.persons = {

    "IDabc": {
            name_de: "Markus",
            name_en: "Mark",
            age: 20,


        },
        "ID123": {
            name_de: "Andre",
            name_en: "Anrew",
            age: 30,
            description: "He is the father of xyz and . . .",



        },

        "IDxyz": {
            name_de: "Isaak",
            name_en: "Isaac",
            age: 23,


        }   

};

});

html:

body ng-app="app">
  <div ng-controller="firstCtrl">
<input ng-model="query" placeholder="Suche . . .">
<ul>
    <li ng-repeat="p in persons | toArray | orderBy:'age' | filter:query"> {{p.name_de}} -> {{p.name_en}} </li>
</ul;
     </div>
   </body>

Answer №2

Regarding your inquiry,

I was able to use an Array of persons, but I require the "ID's", hence the necessity for objects!?

Could you please add ID as a property to your person objects so they appear like this?

$scope.persons = [
    { id: "ID123",
      name_de: "Andre",
      name_en: "Anrew",
      age: 30,
      description: "He is the father of xyz and . . .",
      . . .
    },
    { id: "IDabc",
      name_de: "Markus",
      name_en: "Mark",
      age: 20,
    },
         . . .
];

If you want to search by name_de AND name_en (or any other properties), you can create a custom filter. It's quite simple.

var app = angular.module("YourApp");
app.filter('MyCustomFilter', function(){
    return function(objects, criteria){
        if(!criteria)            
            return objects;

        var filterResult = new Array();
        for(var index in objects)
            if(objects[index].name_de.indexOf(criteria) != -1 || objects[index].name_en.indexOf(criteria) != -1)
                filterResult.push(objects[index]);
        return filterResult;
    }
});

Your HTML code will resemble this:

<input type="text" data-ng-model="personFilter" />
<div data-ng-repeat="person in persons | MyCustomFilter:personFilter"> ... </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

Attempting to insert an empty <option> into a dropdown menu using jQuery and ajax functionality

I'm working on a JavaScript function that dynamically populates a select dropdown based on the value of another select dropdown. I want to include an empty option at the beginning. Here is the code snippet for the function: function createParkFloorM ...

Clever ways to refresh the current page before navigating to a new link using ajax and jQuery

Here's a different perspective <a href="{{$cart_items->contains('id',$productItem->id) ? route('IndexCart'): route('AddToCart')}}" class="item_add" id="{{$productItem->id}}"><p class="number item_price ...

Using Angular's ui-router to achieve a dynamic view based on conditions

I have a question that is similar to the one asked here: UI Router conditional ui views?. However, my scenario is more intricate and I am struggling to make the suggested solution work for me. Essentially, I have a URL that can be displayed in two distinc ...

Error in Highcharts: The property '0' is undefined and cannot be read

Attempting to integrate data from a REST API into HighCharts, but encountering an issue: TypeError: Cannot read property 'series' of undefined. This function retrieves the data from the API: $scope.myData = function(chart) { HighCharts.query ...

Scanning barcode and Qrcode with Angular js HTML5 for seamless integration

Looking to scan Barcode and Qrcode on Android, iPhone, and iPad devices for a project that is built on AngularJS and HTML5 as a mobile website. The requirement is not to download any third-party native application on the device, ruling out the use of nati ...

What is the best way to control the amount of rows displayed in my gallery at any given time?

I need help with customizing my gallery that is dynamically generated from a directory using PHP. My goal is to display only 2 rows of 4 images each, totaling 8 images, with a "show more" button for loading additional rows. How can I set a limit on the n ...

Leveraging the power of React's callback ref in conjunction with a

I'm currently working on updating our Checkbox react component to support the indeterminate state while also making sure it properly forwards refs. The existing checkbox component already uses a callback ref internally to handle the indeterminate prop ...

I attempted various methods but was unable to successfully call the webmethod in the code behind using jQuery Ajax and Knockout

I have attempted various solutions, such as enabling friendly URL resolution and utilizing web method with session enabled, but unfortunately, the issue remains unresolved. I kindly request your assistance in resolving this matter. Here is my HTML code for ...

capturing webpage content with javascript for use in a screenshot

Is there a way to capture a screenshot of a webpage using JavaScript and utilize the canvas tag for this purpose? I attempted to use the html2canvas plugin in the past, but found it lacking in power. I would like to achieve this without relying on extern ...

Having trouble adding a div in React due to the error "Objects are not allowed as a React child"?

While I am rendering the data and displaying it between divs, I keep getting this error: Objects are not valid as a React child (found: Wed Dec 09 1998 00:00:00 GMT+0530 (India Standard Time)). If you meant to render a collection of children, use an ...

The tag's onclick function that was dynamically created was not triggering in jQuery

I created a web application using jquery mobile and ran into an issue. I am trying to call a function by clicking on a dynamically generated anchor tag, but it's not working and showing an error that the function is not defined. Any assistance on this ...

Angular encountered an issue while attempting to access the property 'results' of an undefined value

I've got the code functioning perfectly, but for some reason I'm not getting any errors in the console log. It seems like I can't access results from an indefinite property. Any ideas on what could be causing this issue? I'm trying to m ...

Constantly showing blank white pages on my website specifically in Internet Explorer 11

I successfully developed a website using react, babel, webpack, and backend Django framework. Everything runs smoothly on Chrome, Safari, and Firefox, but when it comes to IE11, issues arise. Initially, the site functions properly, but after navigating thr ...

What is the best way to apply focus to a list element using Javascript?

I recently created code to display a list of elements on my webpage. Additionally, I implemented JavaScript functionality to slice the elements. Initially, my page displays 5 elements and each time a user clicks on the "show more" link, an additional 5 ele ...

The code encountered a parsing error at 11:1, due to the presence of

I'm having trouble with this code. I've searched for answers but haven't found any solutions. Here is the error message: 11:1 error Parsing error: Unexpected token } ✖ 1 problem (1 error, 0 warnings) npm ERR! code ELIFECYCLE npm ERR! ...

Using AngularJS $http.put method with ASP.NET MVC controller may encounter issues and not function as expected

Attempting to develop a straightforward webpage for sending data to the server using $http.put. Script code <script> var myApp = angular.module("myApp", []); myApp.controller("HttpPostController", function ($scope, $http) { $scope.SendHttpPost ...

Submitting a form using AJAX without specifying the form ID when there is a change

I have a unique setup on my page where a table is created with each cell acting as a form. The goal is for these forms to submit when the input value changes (onchange) without refreshing the entire page. An example scenario would be allowing users to ent ...

Tips for assigning an AngularJS data-bound value to the href attribute of an anchor tag

I need to include multiple email ids separated by commas from an angularjs binded value in the mailto field of an anchor tag. The team.emails variable can contain either a single email id or multiple email ids separated by commas. <tr ng-repeat="team ...

Creating header menus with section labels in Windows 8 Metro can be easily accomplished by utilizing Javascript

Is there a way to create a navigation menu in Windows 8 Metro JavaScript that includes header menus and section labels, similar to the example shown below? ...

How can I set the input tag to reset back to 1 when a certain event occurs?

I am currently developing an HTML Snakes And Ladders game. On the settings screen, there is an input field where users can select the size of the board. Depending on their choice, they will be able to choose a maximum number of snakes and ladders. For exa ...