What's causing the problem with my custom filter?

I've encountered an issue with a custom filter I'm currently working on. The challenge lies in the fact that I'm using Angular 1.3.6 and am unable to upgrade at the moment. Therefore, I truly need your assistance with this matter.

Check out this Plnkr

When you type 1H, the filter successfully displays all the leagues with those characters, which is great. However, if you type something like College, it only shows sports starting with College and hides the leagues under those sports. My filter works well for leagues, but not when trying to search for specific sports. I want the filter to show all sports along with their respective leagues when searching through sports.

It's important for me to maintain the current behavior when filtering leagues, as it works perfectly. The problem arises when searching for sports. Below is a snippet of my code:

filter.js

.filter('myFilter', function() {
    return function(sports, filterBy) {
      if (!sports || !filterBy) {
        return sports;
      }

      filterBy = filterBy.toLowerCase();
      return sports.filter(function(sport) {
        return (sport.name.toLowerCase().indexOf(filterBy) > -1) || sport.leagues.some(function(league) {
            return league.name.toLowerCase().indexOf(filterBy) > -1;
          });
      });
    };
  });

sportsLeagues.html

<div ng-repeat="sport in sportsFilter = (sports | myFilter:query)">

   <strong>{{sport.name}}</strong>

     <div ng-repeat="league in sport.leagues | filter: { name:query }">

       <div>{{league.name}} </div>

     </div>

</div>

Answer №1

Create a new filter for the sports leagues that will display all leagues if the sport's name contains the search query, otherwise it will filter them normally:

myApp.filter('leaguesFilter', function () {

  return function (leagues, filterBy) {

    if (!leagues || !filterBy) return leagues;

    filterBy = filterBy.toLowerCase();

    if (leagues[0] && leagues[0].sport.name.toLowerCase().indexOf(filterBy) > -1) return leagues;
    else return leagues.filter(function (league) {
      return league.name.toLowerCase().indexOf(filterBy) > -1;
    });
  };
});

Example: http://plnkr.co/edit/0vYKtBETxDx1tD3udO9Z?p=preview

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

Text aligned at the center of the Y and X axis

I am looking to center my content along the Y axis instead of only on the X axis. To prevent the page from expanding beyond its current size, I have applied the following CSS: html { overflow-y: hidden; overflow-x: hidden } What I want to achieve is havi ...

Invoking a function beyond the boundaries of an Angular application

The Angular code I have is structured within a single module and controller. app.controller('MainCtrl', function($rootScope, $http) { $rootScope.graph = {'width': '100%', 'height': 500}; $rootScope.rectangl ...

Basic HTML and JavaScript shell game concept

After spending several days working on this project, I am struggling to understand why the winning or losing message is not being displayed. The project involves a simple shell game created using HTML, JavaScript, and CSS. I have tried reworking the JavaSc ...

In Javascript, create a variable that dynamically updates for every child element

While this might appear to be a simple question, it has been troubling me for some time now. Let me elaborate on what I am trying to accomplish. I have a collection of images in a gallery, and my goal is to center each image vertically within its contain ...

Leverage Firebase cloud functions to transmit a POST request to a server that is not affiliated with

Is it feasible to utilize a firebase cloud function for sending a post request to a non-Google server? It appears that being on the blaze plan is necessary in order to communicate with non-google servers. Essentially, I aim to perform a POST action to an ...

Transforming JSON data from C# to AngularJS

My current challenge involves an array of file names: [HttpPost] public JsonResult GetJSONFilesList() { string[] filesArray = Directory.GetFiles("/UploadedFiles/"); for (int i = 0; i < filesArray.Length; i++) { ...

Tips for explaining the structure of a basic Just functor in TypeScript

I am embarking on my first attempt to create a simple interface in TypeScript, and I find myself questioning every step along the way. The core question that troubles me is: How can I best describe this straightforward Jest matcher extension? /** * @par ...

The Material UI Popover is appearing outside the designated boundaries

In my app, I am using the code below to implement a react-dates picker controller inside a popover element. The functionality works well in most scenarios, but there is an issue when the button triggering the popover is located at the bottom of the screen, ...

Solving runtime JavaScript attribute issues by deciphering TypeScript compiler notifications

Here is a code snippet I am currently working with: <div class="authentication-validation-message-container"> <ng-container *ngIf="email.invalid && (email.dirty || email.touched)"> <div class="validation-error-message" *ngIf=" ...

"Enhance your website with interactive jQuery lightbox buttons for easy navigation

As I explore the jquery lightbox plugin, I find it to be quite straightforward. However, I am curious if there is a way to make the "previous" and "next" buttons of the plugin function without the images needing to be named sequentially (e.g., "image1.jpg, ...

Using jQuery to establish a canvas element and define its dimensions by adjusting its width and height attributes

My attempt at using jQuery to create a canvas element was not quite as expected. Here is the code I tried: var newCanvas = $('<canvas/>',{'width':100,'height':200,'class':'radHuh'}); $(body).append(n ...

Some CSS features might not work properly when using Vuetify alongside Vue.js and Webpack

I believe the issue may stem from my inability to correctly import the JS file for Vuetify, but I haven't been able to pinpoint any errors. It seems that certain CSS functionalities of Vuetify, like list highlight events, are not working in my applica ...

Is there a way to adjust the label elevation for a Material UI TextField component?

I am trying to enhance the appearance of a textfield label, but I am facing some challenges with my code. textStyle: { backgroundColor: '#1c1a1a', border: 0, borderRadius: 0, width: 400, height: 66, display: 'flex&a ...

Is there a way to access comprehensive data pertaining to an ID through Ajax?

I need help with an Ajax call. Below is the code I currently have: $.ajax({ async: true, url: 'test/', type: 'POST', datatype: 'text json', data: { id: id, }, success: function(data) { // Retrieve the da ...

What is the method for accessing a map that has been set in a separate component?

My current setup involves utilizing a Leaflet map with vue2leaflet. The process I follow is quite standard: I import a list of places from a REST Api in the app store (vuex) Following that, during map initialization, the markers are created using the in ...

Tips for ensuring that a nested object in an array contains only a single object

My array is structured like this: [ { object1:{ childObj1:[grandChild1,grandChild2], childObj1, childObj1} }, { object2:{ childObj1:[grandChild1,grandChild2], childObj1, childObj1} }, { object3:{ childObj1:[grandChild1,grandChild2 ...

Is it possible for TypeScript to automatically detect when an argument has been validated?

Currently, I am still in the process of learning Typescript and Javascript so please bear with me if I overlook something. The issue at hand is as follows: When calling this.defined(email), VSCode does not recognize that an error may occur if 'email ...

Moving ThreeJS model during animation (Retrieving model's position without callback function)

I'm in the process of creating a model that showcases the International Space Station orbiting around the Earth using threeJS. Everything is working perfectly except for updating the position of the ISS model. Currently, I have a sphere that orbits th ...

What are the steps to secure an API endpoint using PassportJS?

Within my app, I have integrated Express and AngularJS for functionality. Specifically, I am utilizing express to manage the basic web serving of the angular code through static routes. The angular code interacts with services that connect to API endpoin ...

Incorporating Distinct Items into an Array with JavaScript

There is a Filter object that stores information about different Car Types. The data is fetched via AJAX calls - on the first call, objects 0-10 are created and added to an array. Subsequent calls bring more car types which are also appended to the array. ...