Filtering objects in AngularJS is a complex task, especially when you need to be able to search for a specific value but also consider if that value exists

Struggling to convey my thoughts in English, but here it goes. Imagine two objects linked by colorid:

   $scope.fruits = {{name:"apple",colorid:"1"},etc};
   $scope.colors = {{id:"1",value:"red"};

I've created a table with search and filter functionalities using ng-repeat

   ng-repeat="fruit in fruits | orderBy:sortType:sortReverse | filter:search"

My goal is to ... be able to still see "apple" when searching/filtering for the color "red".

Edit: It's clear that there isn't a direct connection within the ng-repeat with the second object "colors". The straightforward solution would involve iterating through each "fruit" and pushing its color value (red) into the "fruits" object itself. This way, when searching/filtering for "red", the "apple" object remains visible in the search table. Although, I can't help but wonder if there might be an Angular-oriented solution for connected tables and their relationship ids.

Answer №1

It seems like you want to "connect" your arrays by using nested ngRepeat. Here is an example of how you can achieve this:

(function() {
  "use strict";

  angular
    .module('app', [])
    .controller('MainCtrl', MainCtrl);

  MainCtrl.$inject = ['$scope'];

  function MainCtrl($scope) {
    $scope.fruits = [  
       {  
          "name":"apple",
          "colorid":1
       },
       {  
          "name":"mango",
          "colorid":2
       },
       {  
          "name":"papaya",
          "colorid":3
       }
    ];
    
    $scope.colors = [  
       {  
          "id":"1",
          "value":"red"
       },
       {  
          "id":2,
          "value":"green"
       },
       {  
          "id":3,
          "value":"yellow"
       }
    ];
  }
})();
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" />
</head>

<body ng-controller="MainCtrl">
  <input type="text" class="form-control" ng-model="search" placeholder="Search...">
  <ul ng-repeat="fruit in fruits track by $index">
    <li ng-if="filtered.length" ng-bind="fruit.name"></li>
    <ul>
      <li ng-repeat="color in colors | filter: { id: fruit.colorid } | filter: search as filtered track by $index" ng-bind="color.value">
      </li>
    </ul>
  </ul>
</body>

</html>

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

Limiting Ant Design Date range Picker to display just a single month

insert image description here According to the documentation, the date range picker is supposed to display two months on the calendar, but it's only showing one month. I carefully reviewed the documentation and made a change from storing a single va ...

Is there a solution to resolve the Firestore issue stating: "FieldPath.documentId is not a recognized function"?

In my function, I am retrieving data from two collections in Firestore: Media and Users. Inside the Users collection, there is a subcollection containing a list of all the user's movies. The Media collection includes details about each movie. My goal ...

Learn how to import from a .storybook.ts file in Vue with TypeScript and Storybook, including how to manage Webpack configurations

I'm currently utilizing Vue with TypeScript in Storybook. Unfortunately, there are no official TypeScript configurations available for using Vue with Storybook. How can I set up Webpack so that I am able to import from another .storybook.ts file with ...

Error in NextJS: Attempting to access a length property of null

Does anyone have insights into the root cause of this error? warn - Fast Refresh had to perform a full reload. Read more: https://nextjs.org/docs/basic-features/fast-refresh#how-it-works TypeError: Cannot read properties of null (reading 'lengt ...

React displaying an error indicating that the setTimeout function is undefined?

While attempting to integrate the XTK library with React, I encountered an issue where it kept throwing an error stating that the setTimeout function is not a valid function. Surprisingly, my code appears to be flawless and works perfectly fine when used d ...

Utilize jQuery's .append() function to dynamically insert content into your webpage

I currently have tab elements set up like this: <div class="tab-pane fade active in" id="tab-a"> </div> To populate the content of that tab with a JavaScript string array, I am using the following code snippet: var full_list = ""; for (var ...

Pause the ajax response using jQuery

I encountered a simple issue that is causing me trouble. It seems that when I send an ajax request, there isn't enough time to assign the value to the combonews variable: jQuery.ajax({ type: "POST", url: "People.aspx/LoadCombo ...

Pass a notification to a separate function

Issue Looking for a way to send an 'event' to another function using jQuery. The goal is to prevent the removal of a table row before executing certain treatments, and then remove the row. I want to insert a modal window in between these actions ...

Having trouble retrieving data from the database when passing input to a mongoose query using an href tag in Node.js

Welcome to My Schema const AutomationSchema=new mongoose.Schema( {EventName:String, EventDate:String, EventLocation:String, EventDetails:String } ) The Events Model const EventsModel=new mongoose.model("Events",AutomationSchema ...

Incorporating External JavaScript and CSS specifically for a single component

In my Angular 4 application, I have a specific component that requires the use of a js and css file. While most guidelines suggest placing these files in the Index.html file, I prefer to only load them when this particular component is accessed, not on e ...

Incorporating multiple true statements into an IF ELSE structure can enhance the decision-making

I'm struggling with getting a true return value for numbers that are integers and have either 4 or 6 digits - no decimals or letters allowed. The issue seems to be the validation of whether it's really a number and if it has a decimal point. Alt ...

Having difficulty transferring navigation props between screens using react-navigation

Within my ContactList component, I have utilized a map to render various items. Each item includes a thumbnail and the desired functionality is that upon clicking on the thumbnail, the user should be directed to a new screen referred to as UserDetailsScree ...

The type '{}' cannot be assigned to type 'IntrinsicAttributes & FieldsProp'. This error message is unclear and difficult to understand

"The error message "Type '{}' is not assignable to type 'IntrinsicAttributes & FieldsProp'.ts(2322)" is difficult to understand. When I encountered this typeerror" import { useState } from "react"; import { Card } fr ...

Eliminate all elements marked with a particular class when the user clicks outside of a

I am currently building upon a project that I previously started here. Essentially, what I'm doing is dynamically generating tooltip popups that appear next to a link when it is clicked. However, I now need these tooltips to close when any click even ...

Is it possible to alter the parent scope from an AngularJS directive?

I am currently in the process of constructing my initial Angular application, but I am encountering some difficulties while attempting to achieve a specific functionality. The issue revolves around a video container which is supposed to remain hidden until ...

Error: The function $.getScript(...).done cannot be found

Encountered a strange situation here.. . The following code is functioning properly: // this code working perfectly $.getScript( "https://wchat.freshchat.com/js/widget.js" ).done(( script, textStatus )=>{ // run something }); . . However, if ...

A guide on executing multiple Post Requests in Node.js

Currently, I am facing some issues with my code while attempting to make multiple post requests based on certain conditions. The goal is to retrieve data from an online database (Firebase), save it locally, and then delete the online data. Here's wha ...

find all occurrences except for the last of a pattern in javascript

When considering the patterns below: "profile[foreclosure_defenses_attributes][0][some_text]" "something[something_else_attributes][0][hello_attributes][0][other_stuff]" It is possible to extract the last part by utilizing non-capturing groups: var rege ...

The Lightgallery plugin is creating three duplicates of the slides

I am currently facing an issue with a gallery that loads images from an API and displays them using the lightgallery plugin. Upon implementing the lightbox in the correct location (view question here), I discovered that the plugin is generating three slid ...

How can I utilize a variable in a v-for loop as a label for a q-btn in Vue.js?

I have a list: myList = [1, 2, 3, 4, 5, 6, 7, 8, 9] I'd like to generate buttons using this list where the label corresponds to the number: <q-btn v-for="number in myList" v-bind:key="number" color="primary" label=&q ...