How to use Angular filter to sort through an array and select multiple items based

Looking to implement a filter that, when clicked on a specific name, displays only that name:

{'username': 'julio', 'status': 'created'}, {'username': 'julio', 'status': 'running'}

Then, if a certain criteria is clicked, it should display just the object with that criteria:

{'username': 'julio', 'status': 'created'}

Check out the plunkr example: http://plnkr.co/edit/qDUvvBWQtNrLTLgSC8Yq?p=preview

angular.module('app', [])
  .controller('Ctrl', function ($scope) {
  $scope.users = [
    {'username': 'julio', 'status': 'created'},
    {'username': 'julio', 'status': 'running'},
    {'username': 'phillip', 'status': 'running'},
    {'username': 'mats', 'status': 'created'}
  ];

$scope.filtered = [];
$scope.optionProp = '';

$scope.includeItem = function(item, prop) {
    $scope.optionProp = prop;
    var idx = $scope.filtered.indexOf(item);
    if (idx > -1) {
        $scope.filtered.splice(idx, 1);
    } else {
        $scope.filtered.push(item);
    }
}
$scope.filterFn = function(item) {
    if ($scope.filtered.length > 0) {// first time
            console.info( $scope.filtered.length > 0 );
        if ($scope.filtered.indexOf(item[$scope.optionProp]) < 0){
            console.warn( $scope.filtered.indexOf(item.username ) );
            return;
        }
    }
    return item;
  }
})
.filter("unique", function () {
  return function (data, propertyName) {
    if (angular.isArray(data) && angular.isString(propertyName)) {
        var results = [];
        var keys = {};
        for (var i = 0; i < data.length; i++) {
            var val = data[i][propertyName];
            if (angular.isUndefined(keys[val])) {
                keys[val] = true;
                results.push(val);
            }
        }
        return results;
    } else {
        return data;
    }
  }
});
<body ng-controller="Ctrl">
    <div  ng-repeat="user in users | unique:'username'">
        <input type="checkbox" ng-click="includeItem(user, 'username')" />   {{user}}    
    </div>
    <hr />
    <div  ng-repeat="s in users | unique:'status'">
        <input type="checkbox" ng-click="includeItem(s, 'status')"/> {{s}}    
    </div>
    <ul>
        <li ng-repeat="u in users | filter:filterFn">
            <p>{{u.username}}</p>
            <p>{{u.status}}</p>
        </li>
    </ul>
</body>

Answer №1

You can view the live demo here. I've made adjustments to the optionProp by turning it into an array to accommodate multiple property changes. Additionally, I have tweaked both includeItem and filterFn functions accordingly.

<!DOCTYPE html>
<html ng-app="app">
  <head>
<style>
  li {outline: 2px solid gray; padding: 5px; list-style: none;}
</style>
        <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f7e71786a737e6d31756c5f2e31ec61696764e57e3160">[email protected]</a>" src="https://code.angularjs.org/1.3.0-beta.5/angular.js" data-semver="1.3.0-beta.5"></script>
    <script>
'use strict'

angular.module('app', [])
.controller('Ctrl', function ($scope) {
    $scope.users = [
        {'username': 'julio', 'status': 'created'},
        {'username': 'julio', 'status': 'running'},
        {'username': 'phillip', 'status': 'running'},
        {'username': 'mats', 'status': 'created'}
    ];

    $scope.filtered = [];
    $scope.optionProp = [];

    $scope.includeItem = function(item, prop) {
        var idx = $scope.filtered.indexOf(item);
        if (idx > -1) {
            $scope.filtered.splice(idx, 1);
            var idy = $scope.optionProp.indexOf(prop);
            $scope.optionProp.splice(idy, 1);
        } else {
            $scope.filtered.push(item);
            $scope.optionProp.push(prop);
        }
    }

    $scope.filterFn = function(item) {
        if ($scope.filtered.length > 0) {// first time
                console.info( $scope.filtered.length > 0 );
            for (var i = 0; i < $scope.optionProp.length; i++) {
              if ($scope.filtered.indexOf(item[$scope.optionProp[i]]) < 0){
                  console.warn( $scope.filtered.indexOf(item.username ) );
                  return;
              }
            }
        }
        console.log( item );
         return item;
    }
})
.filter("unique", function () {
    return function (data, propertyName) {

        if (angular.isArray(data) && angular.isString(propertyName)) {
            var results = [];
            var keys = {};
            for (var i = 0; i < data.length; i++) {

                var val = data[i][propertyName];
                if (angular.isUndefined(keys[val])) {
                    keys[val] = true;
                    results.push(val);
                }
            }
            return results;
        } else {
            return data;
        }
    }
});


</script>
  </head>

<body ng-controller="Ctrl">
        <div  ng-repeat="user in users | unique:'username'">
            <input id="inputuser" type="checkbox" ng-model="input.chkUser" ng-click="includeItem(user, 'username')" /> {{user}}    
        </div>
        <hr />
        <div  ng-repeat="s in users | unique:'status'">
            <input id="inputstatus" type="checkbox" ng-model="input.chkStatus" ng-click="includeItem(s, 'status')"/> {{s}}    
        </div>
        <ul>
            <li ng-repeat="u in users | filter:filterFn">
                <p>{{u.username}}</p>
                <p>{{u.status}}</p>
            </li>
        </ul>

        Filter dump: {{filtered}}
</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

JavaScript's XMLHttpRequest

My attempt to bypass the WebGoat prompt involved using a combination of javascript code with XMLHttpRequest to send multiple requests, one using GET and the other using POST. The code snippet is as follows: <script> var req1 = new XMLHttpRequest() ...

What sets $(document).on apart from ($ document).on in CoffeeScript?

One of my buddies is incorporating ($ document).on into his CoffeeScript script. I'm curious to know if this differs from the typical $(document).on and, if it does, how so? ...

JavaScript - untimely initiation of await functionality

I'm a beginner when it comes to using async and await, and I could really use some assistance. In my code, there's a function called register which registers a user and sends their data to the server to create a "user profile". However, I'm ...

Passing the v-model property from a child component to a parent in VueJS

Consider a scenario where there is a Vue component structured like the following: Vue.component('child-comp',{ props:['name', 'val'], data: function(){ return { picked: '' } }, ...

What is stopping me from injecting an Angular controller?

After some consideration, I made the decision to alter the way in which I inject my controller. I successfully utilized the "$inject Annotation" method, following the instructions provided here. NetworkInterfaceDetailedViewController.$inject['$scope& ...

Using forEach Loop with Promise.all in Node.js

I am seeking a solution for a task where I need to read a directory, copy its contents, and create a new file within that same directory. function createFiles(countryCode) { fs.readdir('./app/data', (err, directories) => { if (err) { ...

Pass multiple parameters in a single line using FormData() function

I have a question about my React project. Currently, I am using the following syntax: const data = new FormData(); data.append("token", this.props.token); data.append("origin", this.props.origin); .... My question is: Is there a way to condense these ap ...

We are considering implementing Angular 2, however our current application is built with Angular 1.x. Are there any resources available for integrating Angular 2 with Angular 1.x?

Currently, rewriting our app is not an option and we are also hesitant to develop a new app solely for angular 2. We are exploring alternatives to integrate both frameworks gradually for a smoother migration process. ...

React-Redux - Implement a button toggle functionality to display or hide additional information

I am currently working on creating a portfolio. One of the functionalities I am trying to implement is a toggle button that will show or hide the details of a specific work when clicked. I have been learning React and Redux, so this project is a great oppo ...

Despite providing the correct token with Bearer, Vue 3 is still experiencing authorization issues

I am working on a project that involves Vue 3 with a Node Express back-end server and Firebase integration. On the backend server, I have implemented the following middleware: const getAuthToken = (req, _, next) => { if ( req.headers.authori ...

Revisiting Dynamic URL Parameters with React Router and Express

After setting up my React router to navigate '/Article/1/' via a link, everything seems to be working fine. However, I encountered an issue when refreshing the browser as it no longer detects my Article component. MainApp.js import React from & ...

Back up and populate your Node.js data

Below is the Course Schema I am working with: const studentSchema = new mongoose.Schema({ name: { type: String, required: true }, current_education: { type: String, required: true }, course_name: { ...

Javascript code generated by PHP is failing to run

When you select an option from the dropdown below: <select id='dropdown' name='dropdown' onchange='showChart(this.value)'> <option value="1">Foo</value> <option value="2">Bar</value> </select& ...

Tips on Creating a Display None Row with a Sliding Down Animation Using Javascript

I am working with a table that has some hidden rows which only appear when the "show" button is clicked. I want to know how I can make these hidden rows slide down with an effect. Here's the snippet of my code: function toggleRow(e){ ...

Tips for optimizing, reducing and enabling uib-modal to be draggable

Can you please provide me with some methods to minimize and maximize the uib-modal as I have a need for it? ...

In Java, leverage a string array to store variable names and access those variables using the array index in other parts of your

I have a unique idea where I am using a string array to store different variable names and then utilizing an incremental array index to access those variables. I have created a string array called frac[] and added strings like frac1, frac2, frac3, etc. wit ...

Custom providers do not override Angular UrlResolver

In my Angular application, I am trying to implement a custom UrlResolver provider to incorporate cache breaking logic. I came across this question on Stack Overflow: . Unfortunately, it seems that overriding the default compiler UrlResolver using a provid ...

Combining multiple requestBody in an AngularJS http.put request

Can AngularJS http.put method send multiple requestBody parameters to the server? Here is an example of my frontend Angular put method: function XY() { return $http.put(url, { data1: data1, data2: data2 }); And this is how my backend method is struct ...

Icon for local system displayed on browser tab

I am currently trying to set a Browser Tab icon for the local system, but it is not working. However, when using an HTTP static icon, it works perfectly. Can someone please help me understand what the issue might be? PAGE 1 : Icon Not Showing <link re ...

Use Typescript in combination with React/Redux to showcase a dynamic table on the

Looking to create a React TypeScript Redux application that showcases a table using an API endpoint provided at https://example.com/users The goal is to construct a table with 4 columns: Name, Email, City, and Company, utilizing the API response to popula ...