Angular filtering with drop-down selection and input box

I'm dealing with an array of objects that have a boolean property, and I need to create a three-stage drop-down menu. This menu should allow users to view all items, only active items (those with the property set to true), or only trashed items (those with the property set to false). The default view upon page load should display only active items. However, when I try to switch between views using the drop-down menu, all values disappear. How can I resolve this issue? Plunkr link

Here is my JS code:

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



app.controller('FilterController',function($scope){
    $scope.data = [{
        name: 'darrin',
        markedForDelete:true
    },{
        name: 'megan',
        markedForDelete: true

    },{
        name: 'kim',
        markedForDelete:false
    },{
        name: 'winky',
        markedForDelete: false
    }];

    //show all should show both true and false
    //show active should only show true
    //show trash should only show false
    $scope.filterOptions = [{
        name: 'Show all'

    },{
        name: 'Show active'
    },{
        name: 'Show trash'
    }];
    $scope.customFilter = function(data){
        if(data.markedForDelete){
            return true;
        }
        if(!data.markedForDelete){
            return false;
        }
    }
    $scope.name = "Darrin";
})

And here is the HTML code:

<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>

  <link rel="stylesheet" href="style.css" />
  <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="95f4fbf2e0f9f4e7bbffe6d5a4bba5bbed">[email protected]</a>" src="http://code.angularjs.org/1.0.7/angular.min.js" data-semver="1.0.7"></script>
  <script src="app.js"></script>
</head>

<body>
  <div ng-controller="FilterController">
    <input type="text" ng-model="searchText" />
    <select ng-model="filterOptions" ng-options="f.name for f in filterOptions"></select>
    <div ng-repeat="d in data | filter:customFilter ">{{d.name}}</div>

  </div>
</body>

</html>

I'm looking for suggestions on the best way to handle this situation, as well as insight into why changing the drop-down selection results in all values disappearing.

Answer №1

One issue that needs to be addressed is the lack of a storage location for the selected filter option.

// Set default value to the first option.
$scope.selectedFilterOption = $scope.filterOptions[0];

For the HTML:

<select ng-model="selectedFilterOption" ng-options="f.name for f in filterOptions"></select>

Another problem is with the custom filter not considering the selected filter option. It should be modified like this:

$scope.customFilter = function(data) {
    if ($scope.selectedFilterOption.name == 'Show all')
      return true;
    else if ($scope.selectedFilterOption.name == 'Show active' && data.markedForDelete == false)
      return true;
    else if ($scope.selectedFilterOption.name == 'Show trash' && data.markedForDelete == true)
      return true;
    else
      return false;
  }

Plunker Link

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

Should we consider using a boolean-returning function for ng-show?

Will continuously watching a function's value or using it in a directive like ng-show have a performance impact due to the function being called each cycle? Could it be more efficient to simply use a boolean value to determine this, and update that v ...

Adding External JS Files to a Node.js Project

I recently discovered how to incorporate a JS file into Node JS. However, I am facing an issue with two JS files in particular - hashing.js and encoding.js. Within encoding.js, I have the following code: exports = exports || {}; exports.encoding = encodi ...

Issue with 'for' loop iteration over object array

Can someone help me understand why I am getting the unexpected result "6 You have not watched undefined undefined" in the browser console when running this simple code? var films = [{ title: "The Mummy", hasWatched: true, stars: "5 stars" ...

Mastering Protractor for AngularJS testing - Effectively chaining promises for seamless animationswaitForAnimationCompletion

I'm in the process of creating an automated test suite for our company's AngularJS application. I've already developed several test cases that are running smoothly, but I've hit a roadblock with the current test I'm working on invo ...

Plotting only the initial and final point on Google Maps using API

I am currently working on a tracking application that utilizes the Geolocation and Google Maps API. The app is set up to track the user's position using the watchPosition() function. As of now, a new blue icon is displayed every time a new longitude a ...

Tips for Rotating an Object and Returning it to its Original Orientation

An issue with the turnover arises as the axis is connected to the geometry. View now: Rotate now: Rotation required: ...

Tips for passing a parameter in ReactJS to update the state

In my ReactJS app, there is a function that I am calling: Charts.createNpsGraficoRespostas(nps_respostas_vida, chart_nps_vida , self) The implementation of this function is as follows: export function createNpsGraficoRespostas(array_nps_respostas, state ...

mdcolors not displaying correctly within mddialog component in Angular Material

In my mddialog, I attempted to use md-colors to change the background color of a div within the dialog. Unfortunately, it is not adhering to the current theme and instead defaults to the blue theme. md-colors="{backgroundColor: 'primary'}" Has ...

Is it possible to build an AngularJS application without utilizing HTML5?

Having created an AngularJS application, I have noticed that it functions smoothly on modern browsers. However, some of my devices run on old browsers that do not support html5. Unfortunately, I am unable to upgrade these browsers. Is there a method to ope ...

What is the method for linking images to URLs in my carousel?

I am in the process of revamping a confluence page that showcases a variety of visualizations. Here is the code snippet I am currently working with: <div class="carousel"> <img src="image1.jpg"> <img src="i ...

displaying a div repeatedly following an Ajax response

I'm currently working with Laravel and have an HTML block that looks like this: <div class="white-panel"> <div class="media-body"> <h4 class="media-heading"> <!-- Title Goes Here --> </h4> </div> &l ...

Can SVN hooks be incorporated into NPM in a way that is comparable to git hooks?

I want to incorporate an npm script that performs linting and testing before executing an svn commit. If there are any failures during the linting or tests, I want the commit process to halt, similar to a git commit hook. Does anyone have any recommendat ...

Differences Between Data Captured from Form Submissions and Data Obtained Through Ajax

When attempting to incorporate reCAPTCHA into my MVC site, I encountered an issue where it would not validate unless submitted from a form. Here is the current implementation: @using(Html.BeginForm("VerifyCaptcha", "Signup") ) { @ReCaptch ...

Persistence of local storage in iOS and Android web views

I am facing an issue with data persistence in HTML5's localstorage when using ios/android webviews for a hybrid app. I utilize local storage to save necessary data on the HTML side of my app but have encountered some unexpected behavior. Despite not c ...

Extract model and relationship hasMany from a plain SQL query

I'm seeking assistance in advance. Within my program, I am working with two models: Menu and Window, each with their respective associations. db.menus.hasMany(db.windows); db.windows.belongsTo(db.windows); My goal is to create a query that produces ...

What is the best way to refresh my task list using only basic JavaScript?

How can I update the output to reflect changes when deleting an item from a task list? I used the splice method for deletion but it doesn't seem to be working properly. Any insights on what might have gone wrong? (function(){ // Variable t ...

Error message "Function pointer is not a valid function" encountered in Angular version 1.2.25

I am encountering this error sporadically and without any specific pattern. Previously, the page was functioning correctly, but now this error is causing disruptions. Is there a recommended method for debugging or tracing the source of this problem? Err ...

Implement a loading spinner for autocompletion by utilizing an array as data source instead of relying on an

If you're interested in implementing autocomplete using an array instead of an in-memory web API, check out this thread for an example: Here's the updated search function in autocomplete.service.ts: search(filter: {name: string} = {name: '& ...

What is the reason for Vue regular slots being accessible in this.$scopedSlots?

Please have a look at this simple example Testing.vue <template> <div> <slot name="this_is_not_scoped_slots"/> </div> </template> <script> import Vue from "vue"; export default Vue.extend({ ...

Issues with visuals in jQuery.animate

I have nearly finished implementing a slide down drawer using jQuery. The functionality I am working on involves expanding the drawer downwards to reveal its content when the handle labeled "show" is clicked, and then sliding the drawer back up when the ha ...