Removing filters dynamically from ng-repeat in Angular

I am currently using ng-repeat to display a list of staff members:

<div ng-repeat="user in staff | profAndDr">

There is also a custom filter called 'profAndDr' that only shows people with the titles "Dr." and "Prof.":

app.filter('profAndDr', function() {
return function(input) {
    var out = [];
    angular.forEach(input, function(title) {
        if (title.title === 'PROF.'||title.title==='DR.') {
            out.push(title)
        }
    })
return out;
}

However, I now need to add a checkbox that will allow me to show people with the title "Prof. Amaritos" when checked. This means that I will need to remove the filter from ng-repeat if the checkbox is checked.

You can find the code for this on Codepen.

Thank you!

Answer №1

If you want to conditionally determine if your checkbox is checked, you can pass variables into the filter and use them in your AngularJS code.

For example:

<div ng-repeat="user in staff | profAndDr: isChecked">

Then, create a custom filter like this:

app.filter('profAndDr', function() {
    return function(input, isChecked) {
        var out = [];
        angular.forEach(input, function(title) {
            if (title.title === 'PROF.' || title.title==='DR.' || (isChecked && [othercondition])) {
                out.push(title)
            }
        })
    return out;
}

Answer №2

To avoid implementing multiple ng-repeat without a filter, it is advisable to pass a true/false flag to the filter function in order to return the input as is.

Code Snippet:

<div ng-app="staffApp">
    <div ng-controller="StaffListCtrl">
    <label for="amaritos">Show Amaritos</label>
    <input id="amaritos" type="checkbox" ng-model="showFlag">
    <hr />
    <div 
            ng-cloak 
            ng-repeat="user in staff | profAndDr:showFlag">
      {{user.title}} {{user.first}}
    </div>
  </div>
</div>

Filter Function:

phonecatApp.filter('profAndDr', function() {
    return function(input) {
        var out = [];
        angular.forEach(input, function(title) {
            if (title.title === 'PROF.'||title.title==='DR.') {
                out.push(title)
            }
        })
    return out;
    }
});

Answer №3

To implement a filter based on checkbox value, you can pass the checkbox value as a parameter to your filter function. If the checkbox is checked, return the original input. Otherwise, filter out items that do not match certain criteria.

app.filter('profAndDr', function() {
  return function(input, showAmaritos) {
    if (showAmaritos) {
      return input;
    }
    var out = [];
    angular.forEach(input, function(title) {
        if (title.title === 'PROF.'||title.title==='DR.') {
            out.push(title)
        }
    });
    return out;
  }
}

Below is an example of how to use this filter in HTML:

<input id="amaritos" ng-model="showAmaritos" type="checkbox">

<div ng-repeat="user in staff | profAndDr:showAmaritos">

For a working demonstration, check out the improved codepen.

Answer №4

update javascript code

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

"use strict";

app.controller('TeamListCtrl', ['$scope', '$filter', function ($scope) {
$scope.showTitle=false;
$scope.team = [
{
"first": "POZIK",
"last": "GOLDSMITH",
"title": "PROF."
},
{
"first": "LOSHOK",
"last": "GALIMIY",
"title": "DR."
},
{
"first": "SHMOK",
"last": "GOLDSMITH",
"title": "PROF. AMARITOS"
},

] }])

app.filter('profAndDr', function() {
return function(input, toggle) {
var output = [];
angular.forEach(input, function(title) {
if (toggle == false) {
if (title.title === 'PROF.' || title.title === 'DR.') {
output.push(title)
}

}
else if (toggle == true) {
if (title.title === 'PROF. AMARITOS') {
output.push(title)
}
}
})
return output;
}

});

and in your HTML

<input id="amaritos" type="checkbox" ng-model='showTitle'>

Answer №5

To capture the data entered in your form fields, you simply need to create a variable using the ng-model attribute. Once you have stored this value, you can then apply different filters or conditions based on its contents.

http://codepen.io/anon/pen/rNzQxo

I trust this information proves valuable to you.

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

The routing functionality in Angular4 encounters issues when the `router.navigate()` method is used within the callback of a

I am currently working on implementing Google Sign In within my Angular4 app, but I have run into an unusual issue with routing after using router.navigate() in the Google Sign In callback function. To help illustrate this issue, I have created a sample d ...

It seems like I'm having trouble sharing a collection of objects

Hey there, here's where I currently stand. I've got some code that sends an array of items to a .NET WebAPI (c#). var stuff = []; $('#items').find('input').each(function(){ var text = $(this).val(); stuff.push({ ID: ...

What is the correct way to implement the chain populate method in a Node.js application?

I am developing a blog application with node.js and react, utilizing MongoDB and Mongoose's .populate method to fetch data across collections. Currently, I have three collections: Post, User, and Category. Successfully, I managed to link the username ...

How to showcase base64 encoded images in pug (jade) with node.js

Can anyone help with decoding this mysterious data and displaying the image? I'm using pug as my template engine. Below is the questionable data that needs to be shown as an image: /9j/4AAQSkZJRgABAQEAYABgAAD/4QBaRXhpZgAATU0AKgAAAAgABQ ...and so f ...

"Converting jQuery Form into a Wizard feature with the ability to hide specific steps

I'm working on a form where I need to hide a fieldset when a specific event is triggered. Inside the first fieldset, there is a select tag and when a certain option is selected, the second fieldset should be hidden. <form id="form1"> <fi ...

Craft fresh items within HTTP request mapping

I am currently working on a function that subscribes to a search api. Within the map function, my goal is to transform items into objects. I haven't encountered any errors in my code, but the response always turns out empty. Here's the snippet o ...

AngularJS's ng-click attribute is used to call a function within a controller

I am trying to invoke the Supportticket() function from myController on ng-click, but I am encountering issues with it not working as expected. Can someone please assist me with this matter? The Supportticket() method is located within the controller in my ...

Utilize a jQuery selector to target the initial element of every alphabet character

I'm seeking some assistance with jQuery selectors and have a specific scenario that I need help with. Here is the HTML structure I am working with: <ul> <li class="ln-a"></li> <li class="ln-b"></li> <li cl ...

Creating a group object based on ID using react-native and JavaScript - a step-by-step guide

I have an array of objects that I need to reorganize so that each object with the same guid is grouped together. For instance, given this array; [ {"guid":"3a03a0a3-ddad-4607-9464-9d139d9989bf","comment":"text&quo ...

How to update the <DIV> in Angular JS after submitting data?

I am looking for a way to dynamically display the total direct sales in AngularJS without having to reload the page when processing the cart. Previously, I used to reload the page every time the cart was processed. Javascript .controller('CartCtrl& ...

JS/JQuery: Retrieve value from dropdown list or input field

I'm looking for a way for my user to choose a value from a drop-down menu, but if they can't find the right option there, I want them to be able to input a custom value. I've figured out a workaround by deactivating the drop-down and activa ...

Toggle the visibility of items based on the user's login status

Below is the code snippet for when the user is logged out: <div class="fusion-secondary-main-menu"> <div class="fusion-row"> <?php avada_main_menu(); ?> <?php avada_mobile_menu_search( ...

Executing functionality based on changes in Angular bindings

I am working on securing user passwords in my HTML form. Currently, the password field is stored in localstorage like this: In JS: $scope.localStorage = localStorage; And then in HTML: <input id="pass" type="password" ng-model="localStorage.pass" re ...

Multiple instances of Ajax drop-down effects are now available

On my website's staff page, I have implemented a dropdown menu using AJAX to display information about each member of the staff. The issue arises when attempting to open multiple dropdown menus on the same page - the second dropdown that is opened ten ...

The Vue JS task manager is unable to remove completed tasks from the list

I'm encountering an issue with the 'DELETE ONLY FINISHED' button. The goal is for this button to delete all finished tasks. When a task is completed, its 'finishedTask' property changes to true. I have attempted to store all finish ...

The condition in a Typescript function that checks for strings will never evaluate to true

I encountered a strange issue with a TypeScript condition in a function. Here is my current code, where the parameters are passed from outside: getLevel(validation: string, status: string): string { let card = ""; if (validation == &qu ...

Is there a way in Angular Material to consistently display both the step values and a personalized description for each step?

Is there a way to display both numerical step values and corresponding custom text in Angular Material? I prefer having the number at the top and the descriptive text at the bottom. Check out this image for reference: https://i.stack.imgur.com/LGMIO.png ...

Access account without providing all necessary identification documents

I'm currently facing an issue with my User Schema, as I initially defined 3 inputs for name, surname, and email. However, I now want to allow users to log in only with their email and password, without having to input their name and surname. How can I ...

Having EventListeners set up across a single CSS class returns null when applied to different types of elements simultaneously

I want to create floating labels that resize dynamically when an input is clicked, similar to modern forms. I am using vanilla JS exclusively for this task. Currently, the setup works with the <input> tag. However, it does not work with the <text ...

Cannot get the before-leave transition JavaScript hook to function properly in Vue.js

I am facing an issue with my variable, transitionName, in the beforeLeaveHook function. Despite attempting to change it to 'left', the value remains stuck at 'right'. Any assistance on resolving this matter would be greatly appreciated. ...