Creating a personalized filter using radio buttons in AngularJS

Having multiple radio buttons, I aim to filter results retrieved from a web API based on the selected radio button.

HTML

<div class="row">
    <div class="small-8 medium-9 large-10 columns">
        <ul class="no-bullet">
            <li data-ng-repeat="course in courses">
                <a href="#/CoursesWillStart/{{ course.ID }}">{{ course.CourseName }}</a>
            </li>
        </ul>
    </div>

    <div class="small-4 medium-3 large-2 columns">
        <ul class="no-bullet">
            <li>
                <label><input type="radio" name="filterRadio" value="RadioAll" data-ng-model="filterRadio"  /> All</label>
            </li>
            <li>
                <label><input type="radio" name="filterRadio" value="RadioToday" data-ng-model="filterRadio" /> Today</label>
            </li>
            <li>
                <label><input type="radio" name="filterRadio" value="RadioThisWeek" data-ng-model="filterRadio" /> This Week</label>
            </li>
            <li>
                <label><input type="radio" name="filterRadio" value="RadioThisMonth" data-ng-model="filterRadio" /> This Month</label>
            </li>
            <li>
                <label><input type="radio" name="filterRadio" value="RadioSpecificDate" data-ng-model="filterRadio" /> Specific Date
                    <input type="date" name="from" data-ng-model="from" data-ng-show="filterRadio == 'RadioSpecificDate'" />
                    <input type="date" name="to" data-ng-model="to" data-ng-show="filterRadio == 'RadioSpecificDate'" />
                </label>
            </li>
            <li>
                 <button class="my-button" data-ng-click="filterCourses(filterRadio)">Search</button>
            </li>
        </ul>
    </div>
</div>

Javascript (relevant)

myApp.controller('CoursesWillStartCtrl', ['$scope', 'GetCoursesWillStart',
function ($scope, GetCoursesWillStart) {

    $scope.filterRadio = 'RadioAll';

    $scope.filterCourses = function (filterRadio) {
        switch (filterRadio) {
            case 'RadioToday':

                $scope.courses = coursesStartToday();
                break;

            case 'RadioThisWeek':

                $scope.courses = coursesThisWeek();
                break;

            case 'RadioThisMonth':

                $scope.courses = coursesThisMonth();
                break;

            case 'RadioSpecificDate':

                $scope.courses = coursesInSpecificDate($scope.from, $scope.to);
                break;

            default:    //all
                $scope.courses = GetCoursesWillStart.query();
                break;
        }

    };

    $scope.filterCourses($scope.filterRadio);
}
]);

This marks my debut web application in Angular. While the code above appears functional, I seek to avoid altering $scope.courses to prevent unnecessary retrieval of all courses post each filtration, and to refrain from overusing the web API.

Considering crafting a custom filter, I came across this tutorial. However, uncertain how to tailor it to meet my filtering needs, may someone elucidate how to create a custom filter or suggest an alternative approach for achieving the desired outcome?

Answer №1

This link I found was incredibly helpful, providing a comprehensive explanation of filters in AngularJS. My issue was with reading values from the view to apply them in the filter.

Fortunately, Angular handles this seamlessly with syntax like:

course in courses | filterByDate:filterRadio

Now I can pass filterRadio as an argument to the filter function:

angular.module('myAppFilters', []).filter('filterByDate',
function () {
    return function (courses, filterRadio) {
         //I also moved the switch logic here from the controller    
    }
});

In addition, it's possible to send multiple parameters from the view like so:

course in courses | filterByDate:filterRadio:from:to

An important feature in Angular is alias naming:

course in courses | filterByDate:filterRadio:from:to as coursesFiltered

With this setup, we can easily access the length using coursesFiltered.length

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 loop through an object and show each item in its own row?

My goal is to loop through an object where each item has a type property. The objective is to iterate through the objects and display them in rows based on their type. Currently, it looks like this: https://i.sstatic.net/8iTtG.png I aim to have Frontend, ...

Creating a responsive database using an Express application and Socket.IO

As I am developing an application using Express Create App, specifically designed to run on Plesk hosting, I have already configured it following the example provided by the official Plesk Node Express project. Everything is working smoothly so far. The ap ...

What's preventing me from invoking this object's function through an inline anchor?

CSS: <div class="box"> <p>This is a box</p> </div> Javascript: var box = { content : (function() {return ("This is the content of the box")}) }; alert("Box content: \n" + box.content()); $("output").text( +"<br/ ...

Implementation of internationalization into a JSON-formatted data file

I recently integrated i18n into my application and I'm facing a challenge with implementing the useTranslation(); function in my navbar data file. This file serves as the database for the page titles and tabs, and I'm unsure about how to proceed. ...

What is the best way to access array values in PHP using localStorage?

I attempted to transfer data from JavaScript to PHP Javascript <script type="text/javascript"> const formData = JSON.parse(localStorage.getItem('formdata')); const locationArray = formData.getthelocation.split(',') ...

Displaying certain properties conditionally on an HTML document is a necessary

Is there a way to dynamically display an asterisk on a required field based on the value of a selected radio button using JavaScript? <p class="signatoryLabelAdditional" ng-class="{required:!currentQuoteQto.preferredBillingCity}" translate>qrDe ...

A duo creating art on a shared canvas

I have encountered an issue while developing a real-time paint app using HTML5 canvas. Everything works fine when a single user is drawing on the canvas, but problems arise when two users try to draw simultaneously. For example, if one user changes the col ...

jQuery for Revealing or Concealing Combinations of Divs

UPDATE: Check out this answer. I have a complex query related to jQuery/JavaScript. I came across a post dealing with a similar issue here, but my code structure is different as it does not involve raw HTML or anchor tags. Essentially, I am working on ...

Encountering difficulty when integrating external JavaScript libraries into Angular 5

Currently, I am integrating the community js library version of jsplumb with my Angular 5 application (Angular CLI: 1.6.1). Upon my initial build without any modifications to tsconfig.json, I encountered the following error: ERROR in src/app/jsplumb/jspl ...

Pressing the button does not register outside of the loop function

Just as the title says, I am experiencing an issue where my click event is not being triggered when I click on my button. The button itself was created using a JavaScript loop. Interestingly, I found that when I placed my click event function inside the lo ...

Error occurs in Typescript when attempting to store data in a record using a pointer

When working with nodes and organizing them into a tree structure, I encounter an issue: This is the definition of the interface: interface IDataObj { children: IDataObj[], frontmatter : { type: string, title: string, path: string}, name: str ...

JSON parsing error: Found an unexpected token at character position 43

Attempting to retrieve data from a PHP Server that is running MySQL. Within my angular controller, I utilize $http.get("dbconnection.php") Inside the dbconnection.php file, the code simply selects all entries from the database and returns them. $conn = n ...

AngularJS is encountering infinite digest errors from a $watch function that does not actually trigger any modifications

Within my AngularJS script, I have a single $watch function as shown below: $scope.$watch('[p, q]', function(newVals, oldVals) { $scope.n = newVals[0] * newVals[1]; $scope.phi = (newVals[0] - 1) * (newVals[1] - 1); }); Despite the fact ...

With a GroupAvatar, my Avatar named "max" likes to dance to the beat of its own drum rather than following the rules of my

I am currently working on creating an AvatarGroup using MaterialUi. I have successfully applied a style to all my avatars, except for the avatar that is automatically generated by AvatarGroup when the "max" parameter is defined. const styles = makeStyl ...

Aurelia validator fails to refresh user interface

Despite the aurelia-validator plugin working correctly for form submission and validation, with all properties updating properly, the UI does not reflect any changes. There is no red outline around incorrect properties or error messages displayed. I have r ...

Convert the canvas to an image by right-clicking

Is it possible to treat the canvas element as an image when using drawImage() to draw on it? When I attempt to right click on the canvas element that has been drawn on, the option "Save image as" does not appear. The right click menu displays: What step ...

Show specific button text when no file has been selected

I have a form with an image container that allows users to change the photo. The icon opens a file browser, and when the user selects a file, the Change button submits the photo and updates it. https://i.sstatic.net/R5vwn.jpg If no file is selected, I wa ...

Is it possible to utilize the element tags from a different custom directive as the template for a new custom directive?

Recently started using angularjs and working on a web application that incorporates custom directives. I want users to have the ability to choose which directives they see upon logging in. To achieve this, I am storing the selected custom directive tags in ...

Tips for adding an item to an array within a Map using functional programming in TypeScript/JavaScript

As I embark on my transition from object-oriented programming to functional programming in TypeScript, I am encountering challenges. I am trying to convert imperative TypeScript code into a more functional style, but I'm struggling with the following ...

Beware: The use of anonymous arrow functions in Next.js can disrupt Fast Refresh and lead to the loss of local component state

I am currently encountering a warning that is indicating an anonymous object in a configuration file, and even specifying a name for it does not resolve the warning. Below you will find the detailed warning message along with examples. Warning: Anonymous ...