Filter items by nested properties in ngRepeat

Is it possible to filter a complex object with nested properties using the ng-repeat filter?

Can we achieve this filtering with the ng-repeat filter provided out of the box?

Data

{
  Name: 'John Smith',
  Manager: {
     id: 123,
     Name: 'Bill Lumburg'
  }
}

ngRepeat

<li ng-repeat="e in emps | filter:Manager.Name">{{ e.Name }}</li>

Answer №1

To apply a filter, you must provide the argument:

<input ng-model="filter.key">
<ul>
  <li ng-repeat="e in list | filter: {Manager: {Name: filter.key}}">
    {{e.Name}}  (Manager: {{e.Manager.Name}})
  </li>
</ul>

Check out the example on Plunker

Answer №2

When filtering multiple properties simultaneously, the syntax would resemble the following example.

<ul>
  <li ng-repeat="item in list | {filter: main_property_name: value, nested_property_name: {nested_object_property: value}}">
       ...
  </li>
</ul>

For instance:

        var employees = [name: 'Sarah', roles: [{roleName: 'Developer'},{roleName: 'Designer'}]];

        <li ng-repeat="staff in employees | {filter: name: 'Sarah', roles: {roleName: 'Developer'}}">
              ...
        </li>

Answer №3

To apply multiple deep property filtering, a custom filter needs to be created. In other words, we must develop our own function to filter the data within an object and return the desired object (the filtered object).

For instance, let's say we want to filter data from the following object -

[
{
   "document":{
      "documentid":"1",
      "documenttitle":"test 1",
      "documentdescription":"abcdef"
       }
},
{
   "document":{
      "documentid":"2",
      "documenttitle":"dfjhkjhf",
      "documentdescription":"dfhjshfjdhsj"
       }
}
]

In HTML, the ng-repeat directive is used to display the document list -

<div>
   //search input textbox
   <input ng-model="searchDocument" placeholder="Search">
 </div>
<div ng-repeat="document in documentList | filter: filteredDocument">
   //our html code 
</div>

In the Controller, a filter function is written to retrieve the filtered object based on two properties of the object, which are "document title" and "document description". An example of the code is shown below -

function filterDocuments(document)
        {
            if($scope.searchDocument)
            {
                     if(document.documentTitle.toLowerCase().indexOf($scope.searchDocument.toLowerCase()) !== -1 || document.document.shortDescription.toLowerCase().indexOf($scope.searchDocument.toLowerCase()) !== -1)
                {
                    //returns filtered object
                    return document
                }
            }else {
               return document;
            }
        }

Here, $scope.searchDocument represents the scope variable connected to the search textbox in the HTML input tag, allowing users to enter text for searching.

Answer №4

The most recent update of angularjs now includes a built-in nested object filter, allowing for easy filtering within nested objects. This feature is specifically available for Angular 1 users.

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

Guidance sought on utilizing a callback to retrieve data from mysql using node.js and ejs

I am trying to retrieve the value of foo from the query provided below: exports.get = function(id, cb) { sql = 'SELECT `sidebar`, `test` FROM users WHERE `id` = "' + id + '"'; con.query(sql, function(err, foo) { if (err) ...

The "as" property in NextJS Link does not properly reload the page when opened

I recently started using NextJS and I have a question about its router. I want to link to a page, but I would like the URL to be different. <Link href="/About/About" as="/about-page"> <a> Who We Are <im ...

Error: The connection with mssql in nodejs has been unexpectedly terminated due to a read ECONNRESET issue

I am currently using the node-mssql module which can be found at this link Whenever I try to insert a large amount of data into an MSSQL table, the connection is lost If I attempt to insert more than 4 rows at a time, an error is thrown import * as SQL ...

Retrieving data from a JSON file at 10-minute intervals with Ajax and visualizing it on Google's globe API

After downloading Armsglobe, a globe API provided by Google to draw lines in countries using their names, I noticed that the original code does not fetch JSON data periodically. I attempted to use a simple setTimeout() function in dataloading.js to address ...

Single jQuery scrolling loader malfunctioning in WebKit browser

I've been conducting an interesting experiment in which new entries are dynamically loaded onto a page as you scroll down. Check out a practical demonstration here. In Firefox, everything seems to be working perfectly. However, when viewed in WebKit ...

"Interacting with the ng-keypress event causes the page to smoothly scroll

As a newcomer to angularjs, I am trying to figure out why my component (which simulates a "checkbox" using fontawesome icons) causes the page to scroll down when the user presses the space key. Here is a snippet of my component : ugoFmk.component(' ...

Transforming an array of HTTP Observables into an Observable that can be piped asynchronously

I am attempting to execute a series of XHR GET requests based on the results of an initial request. I have an array of observables representing the secondary requests I wish to make, and I am able to utilize Array.map for iterating over them and subscribin ...

Error 406 occurred when attempting to consume a REST service in org.springframework.web

I am encountering a 406 response error with "HttpMediaTypeNotAcceptableException" when trying to call a REST service from AngularJS. AngularJS REST Call $http.get('/MongoMicroServices-0.1.0/user/getByMailId/' + $scope.username).then(function(re ...

What is the best way to distinguish between various objects that are all in a single line?

After creating an array of objects with data such as name and id, I used the res.json() method to convert it into json format for browser use. However, when I input the array of object data, it looked like this: [ { id: 1, name: 'albany sof ...

The Ajax function effortlessly receives the returned value and smoothly transitions to the error handling stage

When trying to retrieve data from an ajax request, my function needs to receive the returned data as an array of strings. During debugging, I am able to see the response, but at the same time, the error function is triggered. This is how my code looks: ...

Combining or joining two JSON objects within SQL Server

In my database table, I store JSON data in a column and wish to update the existing JSON by merging it with another JSON. Here's an example of what I'd like to achieve: insert into mytable values ('{ "a": "b" ') update mytable set ...

Tap to navigate to queued sections on click

Greetings, community members! Despite my extensive research, I have been unable to find a solution to my query. Just a heads up - I am a novice when it comes to javascript and jQuery. My question pertains to incorporating two image buttons that, upon cli ...

What is the best approach to dynamically enable or disable a button depending on the state of multiple checkboxes in React.js?

Incorporated within a page is a component responsible for displaying multiple checkboxes and toggles. Located at the bottom of this component is a button labeled confirm, designed to save modifications and initiate a backend update request. A new functio ...

Iframe Loading at Lightning Speed

I have set up a script to load my iframe, but I noticed that the script loads the iframe content too quickly. Is there a way for me to configure it to preload all CSS images and content in the background before showing the full iframe content? Here is my ...

Having difficulty looping through JSON information

Currently, I am facing a challenge where I need to iterate through JSON data in order to extract values for specific keys. The data is sourced from an http request and appears as follows: {'1': {'manufacturername': 'SVLJ', ...

Error encountered while making an http get request for a node that returns JSON

I've been struggling with this issue for quite some time now. While I've come across similar problems on Stack Overflow, none of the suggested solutions seem to work for me. I keep encountering the following error message: undefined:1 SyntaxErro ...

Having trouble retrieving data from the API, can anyone help me figure out what I'm doing incorrectly?

Greetings! I am currently working on populating a recyclerview with data fetched from an API. The data includes information from a sub table nested within the main table. Below is the code for better understanding: When dealing with the API JSON, I encoun ...

The issue of the DNN ModuleID not being effectively communicated from the code behind to the ascx component is

Background: I am utilizing a DNN (DotNetNuke) content management system to support VB.NET/Angular1 modules. Currently, I am facing an issue where a value in the code-behind is not accessible in the View.ascx of my module, resulting in a critical runtime e ...

Leverage the object imported from the global <script> tag within a React component

I am currently attempting to incorporate a PayPal button into my React project. As per the instructions provided in PayPal's developer documentation, I have to include <script src="https://www.paypal.com/sdk/js?client-id=YOUR_CLIENT_ID"& ...

Ways to prevent a div from loading an HTML page

When an external button is clicked, the remove() function on id main is triggered. The issue arises when a user quickly clicks on btn1 and then presses the external button, causing the removal to occur before the event handler for btn1. This results in the ...