Вопрос

It seems like custom filters is what I'm going after here. There's a specific behavior I'm looking for when filtering out elements. I'm looking to make a unified search bar to return entire matching group names with all students failing a group name match, group names with just the matching students.

Here's my plunker with all the code

For example, by searching for "er" the results should be the entire listing of "FiddlER Crabs" and "FiERy Skippers" but "Golden Bears" should only show Drew ParkER and ERic.

The plunkr currently demonstrates the default filter behavior. If one changes the filter in the HTML to my custom filter, nestFilter on line 27, and follows the console logs, you can see that the returned array is updating with the addition and removal of search terms but the elements aren't being redrawn. Here's my 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;
};
});
Это было полезно?

Решение

There are a couple of issues with your nestFilter, one of which was that you were modifying to original array (setting cohort.students = matchedStudents).

Here's a working version of the nestFilter (see this Plunker for a demo)

bootTracker.filter('nestFilter', function() {
  return function(elements, input) {
    var filteredCohorts = [];
    console.log(elements);
    angular.forEach(elements, function(element) {
      if (element.name.match(new RegExp(input, 'ig'))) {
        filteredCohorts.push(element);
      } else {
        var matchedStudents = [];
        angular.forEach(element.students, function(student) {
          if (student.name.match(new RegExp(input, 'ig'))) {
            matchedStudents.push(student);
          }
        });
        if (matchedStudents.length > 0) {
          var cohort = angular.extend({}, element);
          cohort.students = matchedStudents;
          filteredCohorts.push(cohort);
        }
      }
    });
    console.log(filteredCohorts);
    return filteredCohorts;
  };
});
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top