Utilize Angular to create a dropdown filter activated by a click event

Having trouble filtering or searching for relevant data using a dropdown input? The task is to select an option from the dropdown and click on the button to filter or display the corresponding data in a table using Angular. Directly achieving this works, but there's an issue with the click event. Seeking assistance as new to Angular. Below is the code:

HTML:


Filter:
    <select ng-model = "filterItem.store" ng-options="item.name for item in filterOptions.stores">
    </select>

    <button>search</button>

<table>
    <tr>
        <th>Name</th>
        <th>Price</th>
        <th>Rating</th>
    </tr>
    <tr ng-repeat="item in   data | filter:customFilter">
        <td ng-click="">
            {{item.name}}</td>
        <td>{{item.price}}</td>
        <td>{{item.rating}}</td>
    </tr>
</table>

JS File:


$scope.customFilter = function(data) {
    if (data.rating === $scope.filterItem.store.rating) {
        return true;
    } else if ($scope.filterItem.store.rating === 6) {
        return true;
    } else {
        return false;
    }
};

//The displayed data
$scope.data = [
    {
        name: "product1",
        price: 198,
        rating: 1
    },
    {
        name: "product2",
        price: 200,
        rating: 5
    },
    {
        name: "product3",
        price: 200,
        rating: 2
    },
    {
        name: "product4",
        price: 10,
        rating: 3
    },
    {
        name: "product5",
        price: 200,
        rating: 3
    },
    {
        name: "product6",
        price: 400,
        rating: 5
    }

Plunker:

http://plnkr.co/edit/RhJic3KYE0Lc42FJ2lOx?p=preview

Answer №1

To simplify the code, you can encapsulate the logic within a function and then invoke that function on a button click event using ng-click directive,

 $scope.filter = function(){
      $scope.filtereddata = [];
      angular.forEach($scope.data,function(key,value){
        if(key.rating === $scope.filterItem.store.rating)
        $scope.filtereddata.push(key);
      })
  }

HTML

   <button ng-click="filter()">search</button>

To display the filtered data, update the ng-repeat directive to iterate over the filtereddata array instead of the original data,

 <li data-ng-repeat="item in filtereddata | orderBy:'price':reverse ">
      Name: {{item.name}} Price: {{item.price}} Rating: {{item.rating}}
 </li>

DEMO

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  
  //Contains the filter options
  $scope.filterOptions = {
    stores: [
      {id : 2, name : 'Show All', rating: 6 },
{id : 3, name : 'Rating 5', rating: 5 },
      {id : 4, name : 'Rating 4', rating: 4 },
      {id : 5, name : 'Rating 3', rating: 3 },
      {id : 6, name : 'Rating 2', rating: 2 },
      {id : 7, name : 'Rating 1', rating: 1 } 
    ]
  };
  
  //Contains the sorting options
  $scope.sortOptions = {
    stores: [
      {id : 1, name : 'Price Highest to Lowest' },      
      {id : 2, name : 'Price Lowest to Highest' },
      ]
  };
  
  //Mapped to the model to filter
  $scope.filterItem = {
    store: $scope.filterOptions.stores[0]
  }
  
  //Mapped to the model to sort
  $scope.sortItem = {
    store: $scope.sortOptions.stores[0]
  };
  
  //Watch the sorting model - when it changes, change the
  //ordering of the sort (descending / ascending)
  $scope.$watch('sortItem', function () {
    console.log($scope.sortItem);
    if ($scope.sortItem.store.id === 1) {
      $scope.reverse = true;
    } else {
      $scope.reverse = false;
    }
  }, true);
  
    
   
  $scope.filter = function(){
      $scope.filtereddata = [];
      angular.forEach($scope.data,function(key,value){
        if(key.rating === $scope.filterItem.store.rating)
        $scope.filtereddata.push(key);
      })
  }
  //The data that is shown
  $scope.data = [
    {
      name: "product1",
      price: 198,
      rating: 1
    },
    {
      name: "product2",
      price: 200,
      rating: 5
    },
    {
      name: "product3",
      price: 200,
      rating: 2
    },
    {
      name: "product4",
      price: 10,
      rating: 3
    },
    {
      name: "product5",
      price: 200,
      rating: 3
    },
    {
      name: "product6",
      price: 400,
      rating: 5
    }
  ];
});
<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
 <link rel="stylesheet" href="style.css" />
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">

  Filter:
  <select ng-model="filterItem.store" ng-options="item.name for item in filterOptions.stores">
  </select>

  <button ng-click="filter()">search</button>

  Sort:
  <select ng-model="sortItem.store" ng-options="item.name for item in sortOptions.stores">
  </select>
  <p>
    <strong>Selected Filter dropdown item: </strong> {{filterItem.store.name}}
  </p>

  <p>
    <strong>Selected Sort dropdown item: </strong> {{sortItem.store.name}}
  </p>

  <ul>
    <!-- We are getting the data first, filtering the data and then sorting the data based
    on the select options -->
    <li data-ng-repeat="item in filtereddata | orderBy:'price':reverse ">
      Name: {{item.name}} Price: {{item.price}} Rating: {{item.rating}}
    </li>
  </ul>
  <table>
    <tr>
      <th>Name</th>
      <th>Price</th>
      <th>Rating</th>
    </tr>
    <tr ng-repeat="item in data | filter:customFilter">
      <td ng-click="">
        {{item.name}}</td>
      <td>{{item.price}}</td>
      <td>{{item.rating}}</td>
    </tr>

  </table>
</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

What is the best way to activate a function to control animation transitions?

My goal is to manually control transitions in my HTML using JavaScript code, such as a tween library like TweenMax. Instead of relying on CSS for transitions with classes like .ng-enter, I want to target a JavaScript function: function onEnter() { /* tra ...

Something seems off with the color of the getImageData when using Fabric JS getContext('2d')

Website: Currently, I am working on adding an eye dropper feature to my website. It functions perfectly at a resolution of 1080p, but when tested on higher or lower resolutions, it malfunctions. Here is the basic code snippet: var ctx = canvas.getContex ...

Unable to get Bootstrap tooltip functionality to work with jquery.slim when importing through webpack

After installing bootstrap 4.6.0 and jquery 3.6.0 via npm, I encountered a strange issue when trying to use tooltips. The following code snippet is functioning correctly: import jQuery from "jquery/dist/jquery"; import "bootstrap/dist/js/bo ...

Consistent column heights within each row

I currently have Bootstrap implemented on my website and have integrated jQuery to adjust the height of each column to match the tallest one. However, the issue I am facing is that the height adjustment applies globally across the entire page, rather than ...

The WebDriverIO browser.Click function encountered difficulty locating an element while using Chrome, but it is functioning properly on Firefox

Currently, I am utilizing WebdriverIO in combination with CucumberJS for testing purposes. The following code functions correctly in Firefox; however, I encounter errors in Chrome which display element is not clickable. I am seeking a solution using JavaSc ...

Troubleshooting: Issue with Passing Variable from Controller to Partial in Rails with AJAX

I am facing an issue with passing a variable from my controller to a partial asynchronously. My goal is to render a form on my view after the user selects an option from a drop-down menu. However, I keep encountering the following error: undefined local v ...

What steps should I follow to include a message in the custom form validation rule in my React application?

I'm currently developing a chat application using React 18 and Firebase 9. For cleaner form validation, I have integrated the Simple Body Validator. Within the Register form, there's an input field of type file for uploading user avatars. The ...

Leverage a pair of conditions to display HTML content within a React component

I am attempting to display an HTML div based on whether a condition has one of two values. The wizard input is changing the responseType variable to either "textMessage" or "textToSpeech". I'm unsure if I have set up the condition correctly... const ...

Mastering Data Labels in ng2-chart: A step-by-step guide

Once again, I find myself battling my Angular and JavaScript challenges, each question making me feel a little less intelligent. Let me walk you through how I got here. In my most recent project, I wanted to enhance the user experience by incorporating sl ...

Exploring Navigation in AngularJS with ui-router

I've encountered an issue with ui-router functionality in my code. Here's a breakdown of the problem: Within my index.html file <li> <a ui-sref="day2">Day 2</a> </li> <li><a ui-sref="day3">Day 3</a& ...

I'm having trouble with installing nx as it keeps showing the error message 'Platform Dependency for NX is Missing.'

I encountered an issue when running npm install: $ npm i npm WARN deprecated @babel/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b5b475e4c4245065b59445b44584a470648474a5858065b59445b4e595f424e586b1c051a13051d">[email  ...

Learn how to update a fixed value by adding the content entered into the Input textfield using Material-UI

I made a field using the Input component from material-ui: <Input placeholder="0.00" value={rate} onChange={event => { this.setState({ `obj.rate`, event.target.value }); }} /> Whenever I input a rate into this field, ...

The jQuery click event to change the color function is functioning properly, but there seems to be an issue with

I'm having trouble changing the font-family using the code below, even though the color is changing properly. What am I missing here and how can I correct it? $(document).ready(function(){ $("body").on("click",".selectableColor", function(){ ...

Switching up the content of an HTML page with JavaScript or JQuery: what you need

Is it possible to update HTML content using JavaScript or JQuery? https://i.sstatic.net/EWOXg.png I am trying to change the contents from 1 to 5 in a sequential order based on the time shown in the image. How can I achieve this using JavaScript or JQuery ...

What is the process for altering the field names within a response from an express GET request?

At the moment, my express API has the following functioning code: router.get('/Find', function(req, res, next){ Dog.findOne({ 'Date_Time_Competed': req.query.Competed }).then(function(dog){ res.send({ ...

Ways in which elements can be toggled through jquery or javascript?

There are various words listed below: word1 word2 word3 ... Every word in the list is linked to 1 to 3 examples. When a user clicks on a word, certain actions should take place. I want the examples to display when the associated word (e.g., word1) is c ...

AngularJS Cross-Origin Resource Sharing request with a customized header

I'm currently facing issues with enabling CORS on my server while using AngularJS. I am working with Angular version 1.2.16 and below is my server configuration: Header set Access-Control-Allow-Origin "*" Header set Access-Control-Allow-Headers "Cont ...

Ways to dynamically incorporate input fields into a form

My current project involves managing an Asset Management system for a company with multiple locations. This system has the capability to return unused asset items back to storage. I am faced with the task of returning a large number of items, which requi ...

How to access an array mapped to a specific key within an object in JavaScript

Is there a way to access an array mapped to a specific key in a JavaScript object? data = {}; data.key = 'example'; data.value = 'test'; data.list = [111, 222, 333]; Viewing the list of items works fine: alert(data.list); // displays ...

Creating a MEAN Stack application by dividing the user interface and backend code onto separate servers

Looking to set up a MEAN stack application where the UI code runs on one server and the backend code runs on another server. Does anyone know of any Github repositories that demonstrate this type of MEAN project setup? The server with the UI code should no ...