Implementing AngularJS table filters on user click

As a newcomer to angularjs, I am attempting to implement a filter on click. The user will select a source and destination, then click on the filter button. The table should display results based on the input. Upon page load, the table should already contain values specified in the js.

Below is my code:

HTML

<div class="r-filter input-group col-sm-12"> 
        <div class="form-group clearfix">
          <label for="sel1" class="left">Search by Location</label>
          <select class="left form-control" id="source" ng-model="source">
          <option>Select Source</option>
          <option>Mumbai</option>
          <option>Pune</option>
          <option>Goa</option>
          </select>
          <select class="left form-control" id="destn" ng-model="destn">
          <option>Select Destination</option>
          <option>Mumbai</option>
          <option>Pune</option>
          <option>Goa</option>
          </select>
          <button class="btn btn-primary " type="button" id="dropdownMenu1" data-toggle="" aria-haspopup="true" aria-expanded="true" ng-click="filterfunc()">Filter</button>
        </div>


      </div>
      <div class="" >
        <table class="table table-striped table-reponsive table-bordered bus-chart-table">
          <thead >
            <tr>
              <th colspan="2">Location</th>
              <th colspan="3">Bus Fare</th>
              <th rowspan="2"></th>
            </tr>
            <tr>
              <th>From</th>
              <th>To</th>
              <th>Ordinary(Price in Rs.)</th>
              <th>Semi-Deluxe(Price in Rs.)</th>
              <th>Deluxe(Price in Rs.)</th>
            </tr>
          </thead>
          <tbody >
            <tr ng-repeat="record in records | busChartFilter: source: destn">
              <td>{{record.dept}}</td>
              <td>{{record.arr}}</td>
              <td>{{record.ordprice}}</td>
              <td>{{record.sdprice}}</td>
              <td>{{record.dprice}}</td>
              <td><a href="#">Book Now</a></td>
            </tr>
          </tbody>


        </table>
    </div>

JS

AppControllers.filter('busChartFilter', function(){

    return function(records,source, destn){
        debugger

        var filteredData= [];
        for( var i=0; i<=records.length; i++){
            var record=records[i];
            if(source==record.dept && destn==record.arr){
                filteredData.push(record);
            }
        }
        return filteredData;
    }
})

AppControllers.controller("chartController", function($scope){

    $scope.beforefilter={};

    $scope.records = [
        { dept: 'Mumbai', arr: 'Goa', ordprice: 700, sdprice: 1000, dprice:1500 },
        { dept: 'Mumbai', arr: 'Goa', ordprice: 700, sdprice: 1000, dprice:1500 },
        { dept: 'Mumbai', arr: 'Pune', ordprice: 400, sdprice: 800, dprice:1000 },
        { dept: 'Goa', arr: 'Mumbai', ordprice: 700, sdprice: 1000, dprice:1500 },
        { dept: 'Goa', arr: 'Pune', ordprice: 400, sdprice: 800, dprice:1000 },
        { dept: 'Pune', arr: 'Mumbai', ordprice: 700, sdprice: 1000, dprice:1500 },
        { dept: 'Pune', arr: 'Goa', ordprice: 400, sdprice: 800, dprice:1000 }
    ];

});

Thank you in advance!

Answer №1

I implemented some updates -

Code Snippet

app.filter('busChartFilter', function(){

    return function(records,source, destination){
        debugger

        var filteredData= [];
        if((source=='' || source==undefined)  && (destination == ''|| destination==undefined))
         return records;
        for( var i=0; i<records.length; i++){
            var record=records[i];
            if(source==record.dept && destination==record.arr){
                filteredData.push(record);
            }
        }

        return filteredData;
    }
})

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

JavaScript may fail to execute properly if the <!doctype html> declaration is not inserted in the correct syntax

While building a web page, I encountered an issue with my JavaScript code not working when using <!doctype html> or any type of <!doctype> at the top of the page. Can someone explain this error? After researching online, I learned that <!do ...

What are effective ways to eliminate cross-origin request restrictions in Chrome?

Just starting out with angular and trying to incorporate a templateUrl in an angular directive. However, when attempting to view the local html file in the browser, I encounter the following errors --> XMLHttpRequest cannot load file:///Users/suparnade ...

What is the reason behind FieldSelect returning a string instead of an object like FieldCheckbox?

FieldSelect component from Sharetribe documents is giving me a string, while FieldCheckbox is returning a JSON object. In a specific scenario, I want FieldSelect to store a JSON object. How can I achieve this? Below is the code snippet for reference: I& ...

How can you display or conceal an HTML page in Jquery Mobile?

This code snippet is used for toggling the visibility of a div. $("[id*=viewMeButton]").click(function(){ $("[id*=viewMe]").toggle(); $("[id*=viewMeButton]").show(); }); In Jquery Mobile, similar functionality can be implemented to show/hide a ...

What is preventing my hidden field from being filled by a JavaScript function?

I've recently developed a JavaScript function that generates a specific string required for another form on the website I'm currently working on. Initially, I decided to store this generated value in a hidden field and then submit it within an HT ...

What can I do to prevent my panolens.js image from pausing its spin whenever a user clicks on it?

I've been working on setting up a 360 image background that rotates automatically and disabling most user interaction controls. However, I'm struggling with one issue – preventing any form of interaction from the user altogether. Whenever a use ...

Creating a Dynamic Soundtrack: How to Embed an Audio

Success! I finally figured it out, with a little help from everyone. I've been diving into the world of Audio Playlists in HTML and attempted to follow a tutorial on the topic found here: https://www.youtube.com/watch?v=vtZCMTtP-0Y. However, I encoun ...

What is the best way to avoid using ng-repeat for the last item being shown?

I currently have an ng-repeat loop that is dependent on an ng-if condition. Here is the specific code block: <div class="fav-prod-customised> <p ng-repeat="ingredient in product.options" ng-if="ingredient.default_quantity == 0 & ...

Getting started with TinyMCE in Nuxt: A step-by-step guide

I need to incorporate this script into my Nuxt code: <script> tinymce.init({ selector: "#mytextarea", plugins: "emoticons", toolbar: "emoticons", toolbar_location: "bottom", menubar: false ...

Exploring the concept of creating controllers through ui-router

Currently, I am in the process of developing a web application using AngularJS with ES6. As I am still at the initial stage of learning AngularJS, I have encountered some questions that I couldn't find clear answers to on the internet. 1) In my proje ...

I'm having trouble using Discord.js to set up a custom role with specialized permissions for muting users

module.exports = { name: "mute", description: "This command is used to mute members in a server", execute: async function (msg, arg) { const muteRole = await msg.guild.roles.cache.find((r) => r.name == "Mute ...

Encountering issues while attempting to utilize pdf2json in a TypeScript environment

When attempting to import pdf2json (3.0.1) into my Node project using TypeScript, I encountered the following error: "Could not find a declaration file for module 'pdf2json'." I also tried installing @types/pdf2json for TypeScript but found tha ...

Utilizing ASCX to trigger JavaScript functions within an ASPX page

I created a user control named MyListSelect.ascx that contains a list of radio buttons... <%@ Control Language="C#" %> <select> <option disabled selected>Select Options</option> <option> option 1 </opti ...

Typescript encounters ERROR TS1128: Expecting a declaration or statement

Having trouble with a TypeScript error in my game-details.component.ts file that I've been trying to fix for a couple of hours. It's showing up at line 26, column 54 and everything seems correct to me. Interestingly, when I press CTRL + S in my ...

What is the best way to extract a portion of a JSON string?

this.on('success', function(file, responseText) { var theID = JSON.stringify(responseText); alert(theID); window.location.href = ('want to put something here'); }); The ...

"Creating a custom comparator in Angular for sorting objects based on their keys

I am embarking on the challenge of designing a directive that will generate a dynamic table complete with front-end pagination and search functionality. It has become clear to me that in order for the search feature to work effectively, I must implement a ...

Issue with Bootstrap 4.2 modal: Unable to edit input fields, button cannot be clicked, modal does not close

https://i.sstatic.net/vHnVG.png https://i.sstatic.net/MhU3f.png Utilizing Bootstrap 4.2.1, I have a modal that opens via a specific link: <a href="#" data-toggle="modal" data-target="#inviteByEmailPopup" data-backdrop="false" data-keyboard="false"> ...

Detecting click events in D3 for multiple SVG elements within a single webpage

My webpage includes two SVG images inserted using D3.js. I am able to add click events to the SVGs that are directly appended to the body. However, I have encountered an issue with another "floating" div positioned above the first SVG, where I append a dif ...

What could be causing my post request to function properly in POSTMAN but not in my React application?

Here are my POSTMAN headers along with the settings I used to send my POST. It only started working when I switched the Content-Type to application/json. https://i.stack.imgur.com/Xz2As.png https://i.stack.imgur.com/aJtbD.png This pertains to the server ...

Retrieve object containing all identical fields except for one specific field

Looking for help with filtering a JavaScript object [ { "comparing_result": "d_sens", "event": "Require", "master_field": "type_de_donnees", "master_field_ ...