"Utilize Angular to categorize and sort JSON data with drop-down filtering

I have been working on filtering out JSON data using AngularJS. Here is my approach:

angular.module('staticSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.data = {
      multipleSelect: ["classA"]
    };
    $scope.isoffice = function(apps) {

      return apps.type === $scope.data.multipleSelect[0];
    };
    console.log($scope.data.multipleSelect[0]);
            $scope.apps = [{
      "id": "1",
      "type": "classA",
      "name": "Name 1"
    }, {
      "id": "2",
      "type": "classB",
      "name": "Name 2"
    }, {
      "id": "3",
      "type": "classC",
      "name": "Name 3"
    }, {
      "id": "4",
      "type": "classD",
      "name": "Name 4"
    }, {
      "id": "5",
      "type": "classE",
      "name": "Name 5"
    }
    ];
  }]);

Plunker

This method works well when the user selects only one value from the list and "type" is not an array. However, I am now exploring how to filter data in a scenario where users can select multiple values from a list, with data being filtered using the OR condition.

$scope.apps = [{
      "id": "1",
      "type": ["classA","classB","classC"],
      "name": "Name 1"
    }, {
      "id": "2",
      "type": ["classB","classC","classE"],
      "name": "Name 2"
    }, {
      "id": "3",
      "type": ["classC"],
      "name": "Name 3"
    }, {
      "id": "4",
      "type": ["classD","classC"],
      "name": "Name 4"
    }, {
      "id": "5",
      "type": ["classA","classB","classC","classD","classE"],
      "name": "Name 5"
    }
    ];

Plunker

For example, if a user selects class A and Class B, the output should be Name 1, Name 2, Name 5

Answer №1

To achieve this functionality, you will need to create a custom filter.
Check out the Demo for reference. Take a look at the tutorial on creating custom filters.

    angular.module('staticSelect', [])
      .controller('ExampleController', ['$scope', function($scope) {
        $scope.data = {
          multipleSelect: ["classA"]
        };
        $scope.isoffice = function(apps) {

          return apps.type === $scope.data.multipleSelect[0];
        };
        console.log($scope.data.multipleSelect[0]);
       $scope.apps = [{
      "id": "1",
      "type": ["classA","classB","classC"],
      "name": "Name 1"
    }, {
      "id": "2",
      "type": ["classB","classC","classE"],
      "name": "Name 2"
    }, {
      "id": "3",
      "type": ["classC"],
      "name": "Name 3"
    }, {
      "id": "4",
      "type": ["classD","classC"],
      "name": "Name 4"
    }, {
      "id": "5",
      "type": ["classA","classB","classC","classD","classE"],
      "name": "Name 5"
    }
    ];
      }]).filter('multiplefilter', function() {
          return function(arr , filterFrom) {
            var filteredArray = [];
            
          angular.forEach(filterFrom, function (value, key) {
           angular.forEach(arr, function (arrObj, key) {
             if(arrObj.type.indexOf(value) > -1 && filteredArray.indexOf(arrObj) == -1){
               filteredArray.push(arrObj);
             }
           })
          });
          return filteredArray;
    }
  });
<!doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8>
  <title>Example - example-static-select-production</title>


  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>



</head>

<body ng-app="staticSelect">
  <div ng-controller="ExampleController">
    <div ng-repeat="app in apps  | multiplefilter: data.multipleSelect">
      {{app.name}}
    </div>
    <form name="myForm">
      <hr>
      <label for="multipleSelect"> Multiple select: </label>
      <br>
      <select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple>
        <option value="classA">Class A</option>
        <option value="classB">Class B</option>
        <option value="classC">>Class C</option>
        <option value="classD"> Class D</option>
        <option value="classE"> Class E</option>
      </select>
      <br>
      <tt>multipleSelect = {{data.multipleSelect}}</tt>
      <br/>
    </form>
  </div>
</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

Achieving a Transparent Flash overlay on a website without hindering its usability (attention, interaction, form submissions, etc.)

Currently, we are attempting to overlay a transparent flash on top of an iframe which loads external websites. Is there a method to configure the page in a way that allows the transparent flash to be displayed while still allowing interaction with the und ...

The comparison between AJAX and JSON passing and PHP generating HTML versus returning it

Currently, my code looks like this: <li onclick = " function CBAppData( callerObj, data ) { var string = ''; for( a in data ) { debug.push( data[ ...

Finding the value of a radio button dynamically created by jQuery

I am having an issue retrieving the value of a radio button that is generated using jQuery. I suspect there may be some problems with event handling. Below is my code: HTML <div id="divOption1"></div> The jQuery script to generate t ...

I'm experiencing an issue with uploading an image to Firebase as I continue to encounter an error message stating "task.on is not a function."

The console displays a message confirming a successful upload. const sendPost = () => { const id = uuid(); const storage = getStorage(); const storageRef = ref(storage, `posts/${id}`) const uploadTask = uploadString(storageRe ...

Parsing JSON objects nested within other objects on the Android platform

Attempting to Parse a JSON object within another object on an Android device. { "data": [ { "id": "1", "picture": "http://mp3dow.com/images/logo.png", "from": { "id": "1", "name": "name1" } }, ...

Tips for parsing and manipulating a json matrix array within Excel-VBA

Looking to convert JSON text into a JSON object in Excel-VBA, including a matrix/array that needs to be addressed (setting a VBA variable to the value). Previously, I successfully parsed nested/keyed JSON text using the "JsonConverter.parseJSON" method. H ...

Utilizing the no-data-text attribute in v-combobox with Vuetify: Tips and tricks

My application includes a simple combobox, and I am trying to set a default text message to display when there are no entries in the items props. To achieve this goal, I utilized the no-data-text prop by passing a specific variable to it. <v-combobox ...

Controller encountering JSON null data

I am currently working on a feature that allows users to send multiple email/SMS messages by selecting checkboxes. However, I am facing an issue where the data is not being passed correctly from my JavaScript function to the action method - all the data sh ...

Error Encountered While Using JSONArray in JSON-simple Library

Here's a JSON Array that I need to parse using JSON-simple: JSON_STRING = [{"name": "adminparking1", "id": 1},{"name": "adminparking2", "id": 2}] To work with the JSON objects provided by this array, I typically use the following code snippet: ...

Could you provide insight into the reason behind debounce being used for this specific binding?

function debounce(fn, delay) { var timer return function () { var context = this var args = arguments clearTimeout(timer) timer = setTimeout(function () { fn.apply(context, args) }, delay) ...

Loop through a JSON object to dynamically update the value of a specific key

I have a JSON object with keys and values, where some of the values are empty strings. I want to replace those empty values with the corresponding key name. However, when trying to get the value of a key within the loop, it returns undefined. JSON: "Forg ...

What is the best Document Object Model (DOM) to utilize alongside Spider

I want to incorporate the GoogleMaps JavaScript library into SpiderMonkey using the python wrapper, but the absence of a DOM is hindering my progress. Is there a method to inject a DOM into this setup in order to successfully make it function? ...

Calculate the total number of JSON objects that have a specific value equal to

How can I use jQuery to count the number of alarms where almSeverity is "1"? The JSON response from the web service provides the following data: { "notification": "Alarm search is complete", "alarmList": [ { "almId": 1,", "almSeverity": "1" ...

Generate an array filled with random numbers in JavaScript based on specified criteria

Is it possible to fill an array with a specific number of elements, determined by a given function parameter? The task is to populate myArray with 5 numbers within the range of 5 and 15. function populateArray(num, startValue, endValue){ var j, localA ...

The correct conclusion is reached by the function when the console.log statement is placed above the function call

By moving the console.log above the function call, the correct conclusion is reached. I double-checked multiple times by toggling the console.log on and off. Running on node.js v16.4.2. The input data is accurate. I attempted to replicate the issue in a di ...

In the console, a JSON string is displayed, however the PHP variable outputs as null

Below is the snippet of javascript code I am working with: $('.showEditForm').click(function () { var webpagefileID = this.id; if($('#editForm').css('display', 'none')) { $('#editForm').css ...

Determining the availability of a remote source in React: A step-by-step guide

Is there a way to verify the existence of a remote resource, such as a large zip file, without actually downloading the file? What is the most efficient method for checking the presence of the resource? ...

Decoding a JavaScript object when receiving it as JSON through a POST request

While browsing through various SO posts, I came across the statement "javascript is JSON". However, I am struggling to apply this concept in my application. My issue arises when I try to perform a POST request using jQuery. $.ajax({ type: &apo ...

Measuring Page Loading Status using Ajax

I'm still learning Ajax and JQuery, and I've been having a tough time putting this together. My goal is to use ajax navigation to load URLs and implement back and front navigations with popstate. The code below is functional, but I'm facing ...

The Context.Principal is returning as null when making a Web API request

I have developed a web application using ASP.NET (.NET Framework 4.8) and ASP.NET WEB API 2, with SQL SERVER 2016 as the database backend. The app is integrated with Azure AD using OpenIDConnect (authorization code flow). For this specific scenario, I hav ...