Counting items in AngularJS filters: a step-by-step guide

I have a question regarding my jsfiddle example.

Here is the link to my jsfiddle

How can I ensure that it counts the number and only displays once instead of repeating multiple times?

This is my HTML code:

<section class="left" style="border-right:1px">  
    <div class="filter">
    Pant Size
     <div>
        <div ng-repeat="professionalarea in pantsGroup">
            <b><input type="checkbox" ng-model="usePants[professionalarea.description]"/>{{professionalarea.description}}</b>
            <span>({{(filteredPlayers | filter:professionalarea).length}})</span>
        </div>
    </div>
   </div>
</section>

My controller:

$scope.$watch(function () {
    return {
        players: $scope.players,
        usePants: $scope.usePants
    }
}, function (value) {
    var selected;

    //here i want call professionalarea.description and don't pants
    $scope.pantsGroup = uniqueItems($scope.players, 'professionalarea');
    var filterAfterPants = [];        
    selected = false;
    for (var j in $scope.players) {
        var p = $scope.players[j];
        for (var i in $scope.usePants) {
            if ($scope.usePants[i]) {
                selected = true;
                if (i == p.professionalarea.description) {
                    filterAfterPants.push(p);
                    break;
               }
           }
       }        
    }
    if (!selected) {
         filterAfterPants = $scope.players;
    }

    $scope.filteredPlayers = filterAfterPants;        
}, true);

For reference, here is an image:

View Image

Answer №1

Implemented a new function called getDistinctValue to retrieve unique items

Below is the snippet provided:

(function () {
    'use strict';


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

    var uniqueItems = function (data, key) {
        var result = new Array();
        for (var i = 0; i < data.length; i++) {
            var value = data[i][key];
            console.log(value);
            if (result.indexOf(value) == -1) {
                result.push(value);
            }

        }
        return result;
    };
  
  function getDistinctValue(items) {
            var lookup = {};           
            var result = [];

            for (var item, i = 0; item = items[i++];) {
                var name = item.professionalarea.description;

                if (!(name in lookup)) {
                    lookup[name] = 1;
                    result.push(name);
                }
            }           
            return result;
        }

    myApp.service('fileUpload', ['$http', function ($http) {
        this.uploadFileToUrl = function (file, uploadUrl) {
            var fd = new FormData();
            fd.append('file', file);
            $http.post(uploadUrl, fd, {
                transformRequest: angular.identity,
                headers: { 'Content-Type': undefined }
            })
            .success(function () {
            })
            .error(function () {
            });
        }
    }]);

    myApp.controller('myCtrl', ['$scope',  function ($scope) {
       
        $scope.usePants = {};

        $scope.players = [
            {
                name: 'Bruce Wayne',
                shirt: 'XXL',
                pants: '42',
                professionalarea: {
                    idAreaProfissional: 1,
                    description: "IT"
                },
                shoes: '12'
            }, {
                name: 'Bruce Wayne',
                shirt: 'XXL',
                pants: '28',
                professionalarea: {
                    idAreaProfissional: 1,
                    description: "test"
                },
                shoes: '12'
            }, {
                name: 'Bruce Wayne',
                shirt: 'XXL',
                pants: '35',
                professionalarea: {
                    idAreaProfissional: 1,
                    description: "IT"
                },
                shoes: '12'
            }
        ];

        // Watch the pants that are selected
        $scope.$watch(function () {
            return {
                players: $scope.players,
                usePants: $scope.usePants
            }
        }, function (value) {
            var selected;

            //here i want call professionalarea.description and don't pants
            $scope.pantsGroup = getDistinctValue($scope.players);
            var filterAfterPants = [];
            selected = false;
            for (var j in $scope.players) {
                var p = $scope.players[j];
                for (var i in $scope.usePants) {
                    if ($scope.usePants[i]) {
                        selected = true;
                        if (i == p.professionalarea.description) {
                            filterAfterPants.push(p);
                            break;
                        }
                    }
                }
            }
            if (!selected) {
                filterAfterPants = $scope.players;
            }

            $scope.filteredPlayers = filterAfterPants;
        }, true);        

        $scope.$watch('filtered', function (newValue) {
            if (angular.isArray(newValue)) {
                console.log(newValue.length);
            }
        }, true);
    });


    myApp.filter('groupBy',
                function () {
                    return function (collection, key) {
                        if (collection === null) return;
                        return uniqueItems(collection, key);
                    };
                });

})();
<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>  
    <script src="app.js" type="text/javascript"></script>
    <style>
        .gridStyle {
            border: 1px solid rgb(212, 212, 212);
            margin-left: 15px;
            width: 97%;
            height: 130px;
            float: left;
            font-weight: normal;
            padding: 35px 10px 10px 10px;
        }
    </style>
    <title>Upload </title>
</head>
<body ng-app="myApp">
    <div ng-controller="myCtrl">
        <div>

            <section class="left" style="border-right:1px">
                <div class="filter">
                    Pant Size
                    <div>
                        <div ng-repeat="professionalarea in pantsGroup">
                            <b><input type="checkbox" ng-model="usePants[professionalarea]" />{{professionalarea}}</b>
                            <span>({{filteredPlayers.length}})</span>
                        </div>
                    </div>
                </div>
            </section>


            <section class="right" style="border-right:1px">
                <div>
                    <ul>
                        <li ng-repeat="player in filteredPlayers | filter:query">
                            <p><b>Player: {{player.name}}</b></p>
                            <p>Shirt Size: {{player.shirt}} Pant Size: {{player.pants}} Shoe Size: {{player.shoes}}</p>
                        </li>
                    </ul>
                </div>
            </section>
        </div>
    </div>
</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

Executing a separate function after each iteration of an ajax call within a loop using Jquery

I am faced with a situation where an ajax function must be run inside a loop that depends on the array's size. How can I execute another function after the ajax call is completed and outside the loop? Is this achievable? Below is the function: funct ...

The context of the selector causes an error to be thrown

Why does jQuery throw an exception when I attempt to select an element with context? The code is as follows: jQuery('b', "DAS<br/><br/><b>ID</b> = 02<br/><b>NAMA DAS</b> = CITARUM<br/><b>LUAS ...

Is there more to AJAX than just fetching a JSON file?

I am in need of using AJAX to achieve my goal. My aim is to have the content of specific subpages displayed in the HTML markup below when a particular link in a list is clicked. This data can be readily accessed from the database via the CMS's API (I ...

Why is it that the condition of being undefined or not functioning properly in state?

I am currently facing an issue with a piece of code I wrote in React JS. The state variable is not functioning as expected and even after modifying it upon button click, nothing seems to be working. After checking the console, I noticed that the state rema ...

Troubleshooting Python Requests Error: Issue with requests.get(url).json()

When attempting to utilize Python requests, I encounter the following issue: when I aim to ensure that a request is in JSON format, the output for requests.get(url) appears as <Response [200]>. Nevertheless, when using request.get(url).json(), the o ...

When I resize the screen size, my multiple item carousel in Bootstrap is failing to adjust and collapses

Whenever I try to resize the output screen, the carousel collapses and the last few items disappear. I really need the carousel to stay intact even when resizing. Can someone please assist me with this issue? Link to my CodePen ResCarouselSize(); $(w ...

Difficulty in displaying additional search outcomes

I decided to take on the challenge of learning coding by working on a website project that involves creating a simple search site. One feature I implemented is when users search for keywords like "Restaurant" or "Restaurants," they are presented with refi ...

Send an identifier to the following page upon selecting a hyperlink in AngularJS

I am currently working on a project that involves displaying a list of places and allowing users to click on a place to view more details on another page. I would like some guidance on how to implement this feature. Here is the HTML code for Page1: <l ...

Prevent the page from scrolling while the lightbox is open

I am struggling with a lightbox that contains a form. Everything is functioning properly, but I need to find a way to prevent the HTML page from scrolling when the lightbox is active. <a href = "javascript:void(0)" onclick=" document.getElementById(& ...

Unable to retrieve JSON information

Currently, I am working on implementing a dynamic dropdown list feature in a Laravel project. To achieve this, I have decided to use Jquery and Ajax for the functionality. <script type="text/javascript"> $('#country').on('change&a ...

Having trouble with Angular2's Maximum Call Stack Exceeded error when trying to display images?

I am facing an issue in my Angular2 application where I am trying to display an image in Uint8Array format. The problem arises when the image size exceeds ~300Kb, resulting in a 'Maximum Call Stack Exceeded' error. Currently, I have been able to ...

Utilizing db.system.js Function within the $where Clause

Here is an illustration of a basic function that I have saved: db.system.js.save({_id: "sum", value: function (x, y) { return x + y; }}); However, when attempting to call it within the $where clause, a Reference not exist error occurs. <?php $collec ...

How to reference 'this' within a d3 callback when using Angular 7

In an Angular directive, I am trying to access a class-level variable inside a callback function. To achieve this, I used an arrow function but the 'this' keyword is still not pointing to the directive. this.itemRects.selectAll('rect') ...

Experiencing difficulties when uploading information to an API in a React JS application

Trying to Send Data via React to Contact Form API Having issues trying to send input data through the API when clicking submit button. The error encountered is that the API call should look like this Example Link However, it calls in a different way Diff ...

Exploring, navigating, and cycling through JSON in Node.js

I'm currently attempting to extract the titles of front page articles from Reddit's RSS feed and running into some issues. Below is the snippet of code I am working with: //var util = require('util'); //var cheerio = require('chee ...

Change a Vue route parameter from title to id

As I develop a course website, each course is assigned its own page URL. For example, when accessing course number 1, the link appears as http://localhost:8080/course/1 . However, I aim to customize it to display as http://localhost:8080/course/course-name ...

Utilizing JavaScript functions alongside a button within a Handlebars template

My handlebars project has the following structure: Project | +-- server.js +-- package.json +-- package-lock.json | +-- public | | | |-- css | | | + -- style.css | +-- views | | | |-- layouts | | | | | + -- main. ...

Guide on sending a REST request with JSON data as a parameter in AngularJS

I've spent a great deal of time searching on the internet for a clear example on this subject but have not been able to find one. What I'm looking for is a basic demonstration of how to make a REST call using AngularJS where we can pass JSON as a ...

Getting back the output in angularjs service

I have encountered two situations when using the return value of a service in AngularJS. Scenario 1: The following code works perfectly fine var SerFactProv = angular.module("SerFactProv", []) .service('ServiceDemo', function () { return { ...

Implementing Click Event to Dynamically Created div using jQuery

I have recently started using JQuery and I am encountering difficulties in binding functions to a dynamically created div. When the user clicks on a button, new divs are added to a container along with a change in the background color of that container. U ...