Guide on effectively sorting the second level ng-repeat data in a table

I have a collection of data objects that I want to present in a tabular format with filtering capabilities. The current filter, based on the 'name' model, successfully filters the nested object 'family'. However, it does not function as intended...

Desired Functionality: When a user inputs a string, such as 'Ma', I would like the table to display all items where the 'family' string contains 'Ma'. Essentially, I want to display all family members as long as at least one string matches. Here is how the filtered result should look:

Homer    Marge, Bart, Lisa, Maggie
Ned      Maude, Rod, Todd

Sample Code provided below:

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

myApp.controller('MyCtrl', function($scope) {
    $scope.tableData = [
        {id: 1, name: 'Homer', family: ['Marge', 'Bart', 'Lisa', 'Maggie']},
        {id: 2, name: 'Carl', family: []},
        {id: 3, name: 'Lenny', family: []},
        {id: 4, name: 'Clancy', family: ['Sarah', 'Ralph']},
        {id: 5, name: 'Ned', family: ['Maude', 'Rod', 'Todd']},
        {id: 6, name: 'Moe', family: []}
    ];
});
table td {
    padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
    <table>
        <tr>
            Filter family members: <input type="text" ng-model="name">
        </tr>
        <tr ng-repeat="item in tableData">
            <td>{{item.name}}</td>
            <td>
                <span ng-repeat="member in item.family | filter: name">
                    {{member}}{{$last ? '' : ', '}}

                </span>
            </td>
        </tr>
    </table>
</div>

Answer №1

To properly filter the initial ng-repeat, you must specify the property to filter on:

<tr ng-repeat="item in tableData | filter: family && {name: family}">

In this case, the key is to use the property name for filtering purposes.

Check out this demo (Enter myFamily in the search bar)

Update: Remember to remove the inner ng-repeat filter that you had initially added

Answer №2

To solve this issue without using a custom filter, you can implement a conditional filter within the first ng-repeat directive. Here is an example of how you can do this:

<tr ng-repeat="item in tableData | filter: (name.length > 0 || '') && {family: name}">

The use of the conditional statement is necessary because of Angular's behavior where blank arrays are not considered if a filter is added and then removed.

If you would like to see a demo of this solution in action, you can check out the following fiddle link: here

Answer №3

If you're looking to implement a customized filter on your ng-repeat loop, you have the option of specifying a function as the filter. This helpful resource on Stack Overflow provides more insight: custom filter article. The custom filter outlined there ensures that only items in tableData with matching values in the sub array are displayed.

It's worth noting that utilizing lodash can streamline this filtering process.

For a practical demonstration, check out this example on Plunker: Plunker demo

<tr ng-repeat="item in tableData | filter:criteriaMatch(name)">

...

$scope.criteriaMatch = function( criteria ) {
    return function( item ) {
        if(!angular.isDefined(criteria) || criteria === "")
            return true;

        var results = _.filter(item.family, function(n) {
           if(_.contains(n.toUpperCase(), criteria.toUpperCase()))
           {
             return true;
           }
        });

        if(results.length !== 0)
          return true;

        else  return false;

    };
};

Answer №4

Have you attempted utilizing the tableData filter? For example:

<input type="text" ng-model="family">

And

<tr ng-repeat="item in tableData | filter: family">

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

Utilizing AJAX to dynamically update a div on a separate webpage

In my application, I have a page called news.jsp that displays a list of news titles. Users can click on a title to read the full body of the news, which is loaded using AJAX within a span tag on the same page. Additionally, I display the top 5 news storie ...

Updating an HTML element by using the input value in a text field with JavaScript/jQuery

Although it may seem straightforward, I am new to Javascript and struggling to find or create the script I need. I have a list of BIN numbers for credit cards and want to extract the first 6 digits of the card number field to determine the type of card, an ...

Firefox compatibility issue with Angular JS for downloading excel files

I've encountered an issue with my AngularJS code for downloading an Excel file. While it works smoothly in Chrome and Internet Explorer, it fails to function in Firefox. The server response isn't presenting any problems. Here's the code snip ...

Ways to launch a Node.js application on Heroku

Greetings! I recently created a small application using nodeJs and angular with the help of the angular-fullstack generator for grunt. I followed the instructions provided on: https://npmjs.org/package/generator-angular-fullstack. After completing the dev ...

Designing personalized plugins with Typescript in Nuxt

In my Nuxt project, I have implemented a custom plugin file that contains an object with settings called /helpers/settings: export const settings = { baseURL: 'https://my-site.com', ... }; This file is then imported and registered in /plugi ...

JavaScript-based tool for extracting content from Sketch file

My goal is to extract the contents of a .sketch file. I have a file named myfile.sketch. When I rename the file extension to myfile.zip and extract it in Finder, I can see the files inside. However, when I try the same process on the server using Node.js ...

Monitor the completion status of all Ajax requests using only JavaScript

I am aware of the ajaxStop method in jQuery. $(document).ajaxStop(function() { //Do something }); If jQuery is not available, is there a way to achieve this with pure JavaScript instead? If so, could you please provide an example? Thanks ...

retrieve undefined value from redux state in a React Native application

Received the data in reducer but encountering issues accessing it in the component. Below is the connection code: const mapStateToProps =state => { return { name:state.fbLogin.name } } function mapDispatchToProps(dispatch){ ...

Steps for configuring type definitions for an Apollo error response

Apollo's documentation explains that an error response can take the following form: { "data": { "getInt": 12, "getString": null }, "errors": [ { "message": "Failed to get s ...

Swap out a portion of HTML content with the value from an input using JavaScript

I am currently working on updating a section of the header based on user input from a text field. If a user enters their zip code, the message will dynamically change to: "GREAT NEWS! WE HAVE A LOCATION IN 12345". <h4>GREAT NEWS! WE HAVE A LOCATIO ...

Tips for displaying images dynamically in HTML using AngularJS

src={{logo}} var logo = 'localhost:3000/modules/images/default.png' I'm trying to display the image path dynamically, but it's not showing up in the HTML. Do I need to use quotes for src? Can someone please assist me with this issue? ...

Executing an Ajax call to trigger a NodeJS function that executes a bash script

I have created a bash script to generate a JSON file that needs to be parsed and sent to the client-side JavaScript for display. My goal is to achieve this without refreshing the page and without using jQuery. I attempted to use Axios but seem to be facing ...

Do you have to host a node server to run Angular applications?

(say) I am currently working on a project that utilizes Laravel or PHP for the back-end and Angular for the front-end. In my setup, I am using angular.js files from a CDN, which should work fine. However, I find myself confused when tutorials and books me ...

Add a style to every div except for the final one

I've attempted to add a unique style to all divs with the same class within a parent div, except for the last one. Strangely, my code doesn't seem to work as expected for this particular case. Can anyone spot what I might be overlooking? Right no ...

Tips on retrieving the ul list value dynamically using jQuery when it changes

I have a list of countries with their dial codes and country codes. I need to find out which country is currently selected and retrieve its data-country-code using jQuery. Can anyone provide guidance on how to accomplish this? <ul class="country-list ...

What sets apart "import { pick } from 'lodash';" from "import pick from 'lodash/pick';"?

Can you explain the difference between import { pick } from 'lodash'; and import pick from 'lodash/pick'; (Keep in mind that it's 'lodash/pick' in the second one, not just 'lodash'.) How do they each impact ...

Building a query in Javascript by utilizing object keys and values: a step-by-step guide

I am looking to transform an object with various keys and values into a query string format, for example: obj1: { abc: "Abc", id: 1, address: "something" }. The challenge is that this object is generated dynamically, so the numbe ...

Adjust the size of an array based on the specified index

I have an array defined as... let myArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] ...along with a starting index let start = 2 and an ending index let end = 5. I want to resize the array by taking elements from start to end, for example: start ...

Error message: App not defined in Ember App.router

Attempting to set up routing for my app for the first time, but struggling to grasp the logic. I managed to render my templates by adding the following code to my route.js file: import Ember from 'ember'; import config from './config/enviro ...

Issue with AnimeJS Motion Path causing element to deviate from desired SVG path

I'm attempting to use an SVG element and the AnimeJS library to make the orange marker follow the course of this RC car race track. https://i.stack.imgur.com/8FKHC.png Despite my efforts, I am encountering strange and undesirable outcomes. At times ...