Getting a consolidated outcome by selecting from a dropdown menu, pulling data from separate Angular arrays

I am currently facing an issue and I could use some guidance. My problem involves a dropdown menu where I make a selection, which then retrieves matching results from two separate Angular data arrays. In this scenario, I have two Angular scopes named $scope.mSessions and $scope.cSessions. While these arrays contain different keys, they share one common category. To retrieve the relevant data based on my selection, I utilize the <select> tag with options like RED FRUIT, YELLOW FRUIT, and ORANGE FRUIT. For instance, if I choose RED FRUIT, the system will search through both mSessions and cSessions arrays to display

"m_category": ["Apple", "Strawberry", "Pineapple"]
and "category": [{"RED":["YES"]}]. I am contemplating whether to create a new array merging both datasets for string comparison or find a way to access the individual datasets by selecting a dropdown option. I'm unsure about the best approach in this situation and would appreciate any help or suggestions!

To view my code and JSFiddle demonstration first visit: http://jsfiddle.net/missggnyc/ujj18nhv/29/

HTML Code Snippet:

<div ng-app="myFruit">
  <div ng-controller="fruitController">
    <select ng-model="selectedAnswer" ng-options="c.cat for c in mySelection"></select> {{selectedAnswer}}
    <table>
      <tr>
        <td>Session Name</td>
        <td>M Category</td>       
      </tr>
      <tr ng-repeat="m in mSessions">        
        <td>{{m.name}}</td>
        <td>{{m.m_category}}</td>        
      </tr>
    </table>
    <table>
      <tr>
        <td>C Category</td>
      </tr>
       <tr ng-repeat="c in cSessions ">        
        <td>{{c.category}}</td>        
      </tr>
    </table>
  </div>
</div>

Javascript (JS) Code Snippet:

var app = angular.module("myFruit", []);
    app.controller("fruitController", function($scope) {
            $scope.mySelection = [
  {"cat": "RED FRUIT",  "m_category": ["Apple", "Strawberry", "Pineapple"], "category": [{"RED":["YES"]}] }, 
  {"cat": "YELLOW FRUIT",  "m_category": ["Banana", "Pineapple"], "category":  [{"YELLOW": ["YES"]}] },
  {"cat": "ORANGE FRUIT", "m_category": ["Peach", "Nectarine"], "category": [{"ORANGE": ["YES"]}]}
  ];
  $scope.mSessions = [{
    "id": 2,
    "name": "BD20",
    "m_category": ["Apple", "Strawberry", "Pineapple"]
  }, {
    "id": 3,
    "name": "CS03",
    "m_category": ["Banana", "Pineapple"]
  }, {
    "id": 4,
    "name": "MIS99",
    "m_category": ["Peach", "Nectarine"]
  }];

  $scope.cSessions = [{
    "number": 439,
    "name": "FDFG",
    "category": [{"RED":["YES"]}]
  }, {
    "number": 34,
    "name": "CN",
    "category":  [{"YELLOW": ["YES"]}]
  }, {
    "number": 44,
    "name": "PPP",
    "category": [{"ORANGE": ["YES"]}]
  }];
});

Answer №1

If you need to apply a filter to both tables based on a selection, you can use the code snippet below:

Check out this working example: Filter Tables Example

HTML Code:

<div ng-app="myFruit" ng-controller="fruitController">
 <select ng-model="selectedFruit" ng-options="c.cat for c in mySelection" ng-change="myDropdownChange(selectedFruit)"></select> <br/>
 Fruit Selected: {{selectedFruit.cat}}
 <table>
  <tr>
    <td>Session Name</td>
    <td>M Category</td>       
  </tr>
  <tr ng-repeat="m in mSessions">        
    <td>{{m.name}}</td>
    <td>{{m.m_category}}</td>        
  </tr>
</table>
<table>
  <tr>
    <td>C Category</td>
  </tr>
   <tr ng-repeat="c in cSessions ">        
    <td>{{c.category}}</td>        
  </tr>
</table>

JS (Controller):

$scope.mySelection = [
              {"cat": "RED FRUIT",  "m_category": ["Apple", "Strawberry", "Pineapple"], "category": [{"RED": ["YES"]}]}, 
              {"cat": "YELLOW FRUIT",  "m_category": ["Banana", "Pineapple"], "category": [{"YELLOW": ["YES"]}]},
              {"cat": "ORANGE FRUIT", "m_category": ["Peach", "Nectarine"], "category": [{"ORANGE": ["YES"]}]}
          ];
      $scope.mSessions = [{
            "id": 2,
            "name": "BD20",
            "m_category": ["Apple", "Strawberry", "Pineapple"]
          }, {
            "id": 3,
            "name": "CS03",
            "m_category": ["Banana", "Pineapple"]
          }, {
            "id": 4,
            "name": "MIS99",
            "m_category": ["Peach", "Nectarine"]
          }
     ];

      $scope.cSessions = [{
            "number": 439,
            "name": "FDFG",
            "category": [{"RED": ["YES"]}]
          }, {
            "number": 34,
            "name": "CN",
            "category": [{"YELLOW": ["YES"]}]
          }, {
            "number": 44,
            "name": "PPP",
            "category": [{"ORANGE": ["YES"]}]
          }
     ];

    let m_myArray = $scope.mSessions;
    let c_myArray = $scope.cSessions;
    $scope.myDropdownChange =  function(fruitSelected){
        let m_myArray_inner = [];
        let c_myArray_inner = [];
        angular.forEach(m_myArray, function(value, key){
            if(areArraysEqual(fruitSelected.m_category, value.m_category)){
                m_myArray_inner = [{'name': value.name, 'm_category': value.m_category}]
            }
        })
        angular.forEach(c_myArray, function(value, key){
            if(areArraysEqual(fruitSelected.category, value.category)){
                c_myArray_inner = [{'category': value.category}];
            }
        })
        $scope.mSessions = m_myArray_inner
        $scope.cSessions = c_myArray_inner;
    }

    function areArraysEqual( x, y ) {
        // If both x and y are null or undefined and exactly the same
        if ( x === y ) {
            return true;
        }
        // If they are not strictly equal, they both need to be Objects
        if ( ! ( x instanceof Object ) || ! ( y instanceof Object ) ) {
            return false;
        }
        // They must have the exact same prototype chain, the closest we can do is
        // test the constructor.
        if ( x.constructor !== y.constructor ) {
            return false;
        }
        for ( var p in x ) {
            // Inherited properties were tested using x.constructor === y.constructor
            if ( x.hasOwnProperty( p ) ) {
                // Allows comparing x[ p ] and y[ p ] when set to undefined
                if ( ! y.hasOwnProperty( p ) ) {
                    return false;
                }
                // If they have the same strict value or identity then they are equal
                if ( x[ p ] === y[ p ] ) {
                    continue;
                }
                // Numbers, Strings, Functions, Booleans must be strictly equal
                if ( typeof( x[ p ] ) !== "object" ) {
                    return false;
                }
                // Objects and Arrays must be tested recursively
                if ( !areArraysEqual( x[ p ],  y[ p ] ) ) {
                    return false;
                }
            }
        }
        for ( p in y ) {
            // allows x[ p ] to be set to undefined
            if ( y.hasOwnProperty( p ) && ! x.hasOwnProperty( p ) ) {
                return false;
            }
        }
        return true;
    }

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

Form Automatically Submits Data Upon Loading of Page

I am currently facing an issue with my hidden div that is being loaded when I click the submit button. The form is sending results upon page load, and even though I have included the validateForm() function and called it at the end of the submit function ...

What is the best way to utilize a variable declared in a JavaScript file within an HTML document?

Here is the content of my JavaScript file: var moment = require("moment") var structuredDate = moment(Date()).format("LLLL") I am trying to dynamically update a <div> element in my HTML with the date value. This is what I attem ...

The console is displaying a null value outside of the block, however, the correct value is returned when

I am having an issue where the first console.log() is not returning the correct value, but the second one is. Can anyone provide assistance with this problem? angular.module('resultsApp', ['ngCookies']) .config(['$qProvider&a ...

After upgrading from Vuetify version 1.5 to 2.0.18, an issue arises with modules not being found

I encountered the following error: module not found error To address this issue, I took the following steps: Commented out import 'vuetify/src/stylus/main.styl' in the src/plugins/vuetify.js file. Added import 'vuetify/src/styles/main. ...

Tips for creating a Next.js "Link" component with an optional "href" property

I've created a custom React function using typescript for the Next.js Link component. The "href" property is necessary for the "Link" to be used anywhere, so it couldn't be utilized as a button that functions as a submit button in forms. import N ...

Executing the main process function

One of the challenges I'm facing is calling a function from the main process in Javascript while a button is clicked in another file. Here is the code snippet: Main.js const electron = require( 'electron') const {app, BrowserWindow} = elec ...

issue concerning slide functionality and ajax integration

I'm facing an issue with the structure of my HTML. Here is the setup I have: <div id ="slide1"> <form method="post" id="customForm" action=""> //my content - name, email, mypassword, pass2 </for ...

Generating HTML widgets dynamically with jQuery: A step-by-step guide

Looking for a way to display an interactive widget on your page while allowing users to generate multiple instances and interact with them simultaneously? Imagine having a widget like this: <div id="my_widget"> <script type="text/javascript" ...

HTTP GET request not updating data

I'm experimenting with AngularJS and trying out some examples: Here's the HTML code snippet: <html ng-app="myApp"> <body ng-controller="JokesController"> <h1>{{ joke }}<h1> </body> </html> A ...

Change the background color according to the user's input text

I want to create a text box where users can input color keywords like blue, lime, or black. When they click submit, I want the background color of the page to change accordingly. This is what I have so far: <label for="color">Color: </label> ...

Collapse a previously used item when a new item is opened within Angular

I've managed to create a tree structure for a sideBar Menu using this code, and it's working well. However, what I'm trying to achieve is that when a menu with submenus is expanded and the user clicks on another parent menu, the expanded sub ...

Assign a property to an object following the execution of the query

I am currently utilizing node express to achieve a specific functionality. I encountered an issue while attempting to populate a field with data from another field. To resolve this problem, I decided to retrieve the value from another query and then assign ...

Struggling with developing a straightforward application with Angular-Material

My goal is to develop an application that utilizes the Angular Material navigation bar, as showcased in this example. Being relatively new to AngularJS, I'm facing an issue where my app loads but only displays a blank page. Below is the code snippet ...

Having trouble with Instafeed JS loading?

I am currently experimenting with instafeed.js, but I am encountering difficulties getting it to load on a basic bootstrap page. While everything else on my page loads successfully, this particular container remains empty without any Instagram code presen ...

`How can I extract HTMLElements from slots in vue3?`

When attempting to develop a Layer component, I encountered some challenges. Here is the code: // Wrapper.vue <template> <slot v-bind="attrs"></slot> </template> <script lang="ts" setup> import { defi ...

What is causing Vue.js to lag slightly? Why is jQuery necessary to retrieve the current value?

I am encountering an issue with a select element <select id="filter" v-model="filter" @change="changeFilter"> <option value="all">All</option> <option value="one">One</option> <option value="two">Two</option> ...

TypeError occurs when app.use is used with multer configuration

I am currently facing an issue while attempting to set up multer in my app.js file (using node.js/express) for enabling users to upload images. The code snippet in app.js is as follows: // Various require statements including passport, cookie parser, etc. ...

What might be causing the issue with my ajax request to the PHP file within the data parameter?

Although I am successfully getting my php value into a JavaScript variable, it seems like my script.js file is unable to find it. For the sake of brevity, some files have been omitted in this question. The main issue is that the script.js file retrieves th ...

Fetch response headers not being detected by Web Worker

Currently in my chrome extension, I'm utilizing web workers to collect response header cookies from a specific website. Interestingly, when I execute the request on the main thread, the response contains all the expected cookies. However, when the exa ...

Hiding dropdownlist options in an Angular JS application

I have a dropdownlist and I am looking to hide a specific option based on a condition The code I have written is as follows: $scope.sqs.qs6_PropertyType.answer = _.findWhere($scope.propertyType, { id: '2' }); // This code sets the selected va ...