Utilizing custom filters to navigate through nested ng-repeats

My goal is to achieve a specific behavior by using custom filters. I am working on creating a unified search bar that will display entire group names with all failing students, as well as group names with only the matching students.

If you want to see the code, check out my Plunker here

For example, when searching for "er," the results should include "FiddlER Crabs" and "FiERy Skippers" in full, but "Golden Bears" should only show Drew ParkER and ERic.

The current Plunker demonstrates the default filter behavior. By changing the filter in the HTML to my custom filter, called nestFilter on line 27, and observing the console logs, you can see that the array updates with the addition and removal of search terms, but the elements are not being redrawn. Here's my custom filter:

bootTracker.filter('nestFilter', function() {

  return function(elements, input) {

  var filteredCohorts, filteredCohortsStudents;
  filteredCohorts = [];
  filteredCohortsStudents = [];

  console.log(elements);

  angular.forEach(elements, function(cohort) {

    var matchedStudents;
    matchedStudents = [];

    if (cohort.name.match(new RegExp(input, 'ig'))) {
      filteredCohorts.push(cohort);
    }

    angular.forEach(cohort.students, function(student) {
      if (student.name.match(new RegExp(input, 'ig'))) {
        return matchedStudents.push(student);
      }
    });

    cohort.students = matchedStudents;
    if (cohort.students.length > 0) {
      return filteredCohortsStudents.push(cohort);
    }
  });

  console.log(filteredCohorts);
  return filteredCohorts;
};
});

Answer №1

There were a few issues with the nestFilter function, one of which involved mistakenly modifying the original array by setting

cohort.students = matchedStudents
.

Check out this revised version of the nestFilter (click here for a demo)

app.filter('nestFilter', function() {
  return function(items, input) {
    var filteredItems = [];
    console.log(items);
    angular.forEach(items, function(item) {
      if (item.name.match(new RegExp(input, 'ig'))) {
        filteredItems.push(item);
      } else {
        var matchedValues = [];
        angular.forEach(item.values, function(value) {
          if (value.name.match(new RegExp(input, 'ig'))) {
            matchedValues.push(value);
          }
        });
        if (matchedValues.length > 0) {
          var newItem = angular.extend({}, item);
          newItem.values = matchedValues;
          filteredItems.push(newItem);
        }
      }
    });
    console.log(filteredItems);
    return filteredItems;
  };
});

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

Developing applications using ReactJS with Typescript can sometimes lead to errors, such as the "onclick does not exist on type x

In the code snippet below, I have a method that renders a delete icon and is used in my main container. Everything functions correctly except for a small cosmetic issue related to the type any that I am struggling to identify. import React from 'reac ...

Using Javascript to establish a connection with a Joomla MySQL database

Recently, I was tasked with building a website in Joomla that utilizes a MySQL database. As part of this project, I am required to develop a JavaScript function that connects to the MySQL database. Do you have any advice or tips for me? ...

Checking URL validity using JavaScript Regex

I attempted to validate a URL with or without the http protocol, but no matter what I tried, the function kept returning false. I verified my regex string on this website: And it appeared as expected. function isUrlValid(userInput) { var rege ...

jQuery Slider Showing Incorrect Images

My jQuery slider is acting strangely. It hides the first image, shows the second one, but then just repeats the cycle by showing the first image again instead of loading the third one. I'm puzzled about what could be causing this issue in my code. Do ...

Updating Vue 3 asynchronous data doesn't reflect changes when the local settings are modified

I have a dedicated external .js file designed to retrieve data from the backend depending on the website's locale. Check out the code snippet below: import { ref } from "vue"; export function fetchData(section, key) { // Making a GET requ ...

Exploring the differences between objects in AngularJS

My goal is to have comments displayed if a Post contains them. I attempted to use angular.equals, but it doesn't seem to be working for me. Maybe I'm not using it correctly? Below is the Controller code for both Post and Comment. var PostContro ...

Issues encountered with sending post requests to a yii2 application when using Angular4

After implementing the following code: this.http.post('http://l.example/angular/create/', {name: 'test'}).subscribe( (response) => console.log(response), (error) => console.log(error) ); I encountered an error on ...

Preventing JQuery from interrupting asynchronous initialization

I am currently developing an AngularJS service for a SignalR hub. Below is the factory code for my service: .factory('gameManager', [function () { $.connection.hub.start(); var manager = $.connection.gameManager; return ...

Is it possible to create a mouse-following effect with lighting using Javascript

Recently, I've been honing my Javascript skills and decided to create a follow-mouse function. After successfully implementing it, I started brainstorming a new concept that I'm unsure is achievable. Is there a way to develop an "orb of vision" ...

Encountering Error 500 with Jquery Min.Map File

ERROR: GET request to http://domain.com/assets/js/jquery-1.10.2.min.map returned a 500 Internal Server Error Can anyone help me figure out what's causing this error? I checked the log files in /var/log/error but couldn't find any information. T ...

Removing all table rows except one in Jquery

I currently have this code in my view: <script> $(document).ready(function() { $("#add_instruction").click(function(){ $("#instructions").append("<tr><td></td><td><input type='text' name='rec ...

Is there a way to adjust the text color of a label for a disabled input HTML element?

If the custom-switch is active: the label text color will be green. If the custom-switch is inactive: the label text color will be red. A JavaScript (JQuery) method call can be used to activate one button while deactivating another. The Issue It appe ...

Effective monitoring of dependencies in a personalized connection

My goal is to implement a method to visually filter table rows generated by the foreach binding. I want the filtered out rows to be hidden instead of removed from the DOM, as this can greatly improve rendering performance when filter conditions are changed ...

Troubleshooting Issues with jQuery Accordion Buttons

I have a nearly complete accordion that just needs some adjustments. HTML CODE: <footer> <div> <h1>Hide</h1> <h1>Hide</h1> <h1>Hide</h1> <h1>Hide</h1> ...

Determine the truth or falsehood of a key in a multidimensional array using PHP

Having difficulty setting the value of a variable based on three boolean values in a multidimensional array. New to PHP and JavaScript. After var_dumping my form data (passed using $http from angular to an external PHP file), here is what I have: array(3 ...

Adding a Timepicker to a Datepicker on a jsp webpage with javascript

I am working on a JSP page that includes a date picker. I want to enhance this datepicker by adding a start time and end time within the calendar itself. How can I achieve this? Additionally, I need to implement validation ensuring that the start time is a ...

What is the best way to collect and store data from various sources in an HTML interface to a Google Spreadsheet?

Currently, I have a spreadsheet with a button that is supposed to link to a function in my Google Apps Script called openInputDialog. The goal is for this button to open an HTML UI where users can input text into five fields. This input should then be adde ...

What could be causing my header component to rerender even when there are no new props being received?

https://codesandbox.io/s/crimson-field-83hx6 In my project, I have a Header component that simply displays a fixed text and includes a console.log statement: const Header = props => { console.log("header render"); return ( <header> ...

Assistance Required for Making a Delicious Cookie

Within my interface, there are two buttons displayed - one is labeled yes while the other is called no. <input type="button" name="yes" onclick="button()"> <input type="button" name="no"> In order to enhance user experience, I am looking to i ...

Save picture in localStorage

Hello, I am currently working on a page where I need to retrieve an image from a JSON file and store it locally. Below is the code I have been using: <!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-1.10.1.min. ...