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

How can I create a rectangular border around text using the HTML5 canvas?

How can I dynamically draw fitted rectangles around text labels (person's full name) without fixed sizes, taking into account that the labels vary in lengths? Below is the code used to draw the text labels: var ctx = document.getElementById('ma ...

Combining column values with AngularJS

What is the best way to merge column values in AngularJS? ...

Is there a way to distribute my World instance among several step definition files in CucumberJS?

Currently, I am working on implementing a CucumberJS scenario that involves using multiple steps spread out across two separate step definition files. In this setup, the first step establishes certain variables in the World object which need to be accessed ...

Loading content dynamically with AJAX and enabling smooth page scrolling

Looking for a solution to this issue. I have a button on my webpage that, when clicked, uses AJAX to load content into a "div" element below the button. Everything functions properly except for one problem - every time the button is pressed, the page scrol ...

Is it possible to change the return value of an Object key to something other than a string in REACT? Issue with RE

In an attempt to modify the data in an object using the setState method in 'react', I decided to take a different approach. Instead of creating a function for each key in the state object, I attempted to create one object and return the key from ...

What exactly does Container-Based Authorization entail?

Did you know that the "XMLHttpRequest" object includes a method called "open," which has the option to supply a username and password? These parameters can be used for requests that require container-based authentication. Here is the method signature: op ...

Tips for achieving expansion of solely the clicked item and not the whole row

I am trying to create a card that contains a cocktail recipe. The card initially displays just the title, and when you click on a button, it should expand to show the full menu and description. The issue I'm facing is that when I click on one element, ...

processing an array with ng-repeat taking its time

I am facing an issue with slow performance while iterating over an array of objects: $scope.items = {key1: val1, key2: val2, keyx: valx} Within my template, I am using ng-repeat in a table: <tr ng-repeat="item in items"> <td> {{item.key1 ...

Assistance needed with generating unique IDs in MongoDB

Currently, we rely on MongoDB's built-in ids for all of our unique id generation. However, there are specific cases where we must generate an id for an object before adding it to the database. One potential solution is to create an entry, retrieve th ...

Error encountered while attempting to download PDF file (blob) using JavaScript

Recently, I have been utilizing a method to download PDF files from the server using Laravel 8 (API Sanctum) and Vue 3. In my Vue component, I have implemented a function that allows for file downloads. const onDownloadDocument = (id) => { ...

Encountering a 404 Error while using GetStaticPaths in NextJs

Having issues with Next JS dynamic routes resulting in a 404 Error. Initially attempted debugging by setting it up dynamically, then manually at http://localhost:3001/question/62e7b69ca560b1c81aa1a853 but still encountering the same issue. Tried toggling f ...

What causes performance issues when utilizing mouseover events in JQuery?

var mouseX; var mouseY; $(document).mousemove( function(e) { mouseX = e.pageX; mouseY = e.pageY; }); $(".test").mouseover(function(){ $('#DivToShow').css({'top':mouseY,'left':mouseX, 'display':'block&ap ...

Encountered an EACCESS error while attempting to generate package.json in Angular

Upon completing the command line "yo angular" and following all the necessary steps, I encountered this error : Screenshot of the error I attempted to run it using "sudo yo angular" but unfortunately, it did not resolve the problem. Does anyone have any ...

The combination of WASM and Node.js encounters an issue when attempting to utilize 'import.meta' outside of a module

I successfully compiled the FastText C++ module to a wasm module using the provided make file, with the following flags: EMCXX = em++ EMCXXFLAGS = --bind --std=c++11 -s WASM=1 -s ALLOW_MEMORY_GROWTH=1 -s "EXTRA_EXPORTED_RUNTIME_METHODS=['addOnPos ...

Stopping halfway through a jQuery toggle width animation to close again

Perhaps the question may be a bit unclear, but allow me to provide an example. When repeatedly clicking the button that toggles the width, the div continues to animate long after the button press, which is not visually appealing. My desired outcome is for ...

including a content tag into an input field within a template

I'm experimenting with the new html5 template tag to create a versatile form that can be used in various situations without relying heavily on javascript. Check out this fiddle to see what I have so far http://jsfiddle.net/684uH/ My objective is to ...

The if-else statement doesn't seem to be functioning correctly once the else condition is included

I'm currently developing a search function for an address book that iterates through the contact array and displays them in a popup. Initially, it was working correctly by finding and displaying the contacts that were found. However, once I added the ...

How does Socket.io facilitate a basic web socket connection with a specific URL?

My current project involves a client making a WebSocket request to the following URL: ws://localhost:3000/feed/XBTMUR https://i.sstatic.net/R7H9T.png On my server side, I am utilizing NodeJs with express running. I have decided to implement Socket.io in ...

Disabling the intellisense feature for locale suggestions in Monaco is recommended

Switch the keyboard language to a different one (in this case Japanese using alt + shift), and when typing in Monaco editor, an intellisense menu appears with options to remove and search. Monaco Editor Version: V0.33.0 https://i.stack.imgur.com/SIyeV.pn ...

Getting to the values within a JSON object that contains multiple arrays

Is there a way to retrieve array data from the json object data? const [data, setData] = useState([]) const getData = () => { axiosInstance .get(url + slug) .then(result => setData(result.data)) } useEffect(() = ...