Using Angular Filters to Create Counters

Estimated Reading Time: 8 minutes

Angular2.jpgFor those who don’t know, Angular comes with some pretty powerful filters baked right into the system.  They are great for transforming values in a view to look the way we want.  They can also be used to weed out values we don’t want to show.  In addition to this, you can also use these filters in your views to create new variables that can then be used in other places in your views.  At InfoTrust, we recently used this functionality to keep our objects and controller logic more organized.

To demonstrate this, let’s build a quick application that will separate out great drummers that are still alive with those who have passed on to the “Great Drum Set in the Sky.”  The code for this post can be found here.  You can find a demo of the finished product here.  Let’s start by setting up our basic skeleton application.  Create a new directory and put the following in a file called index.html in that directory.


<!DOCTYPE html>
<html lang="en" ng-app="filterTest">
<head>
    <meta charset="UTF-8">
    <title>Angular Filters</title>
    <style>
    [ng:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
      display: none !important;
    }

    #drummer-lists, form {
        float: left;
    }

    #drummer-lists {
        width: 40%;
    }

    form {
        width: 50%;
    }
    </style>
</head>
<body ng-cloak>
<div ng-controller="fooController">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
    (function(angular) {
        var app = angular.module('filterTest', []);

        app.controller('fooController', ['$scope',
            function($scope) {
                console.log('hello');
            }
        ]);
    })(angular);
</script>
</body>
</html>

If you run this file in a web browser and open up the developer console, you should see “hello” printed to the screen.  This means everything is hooked up correctly.  All we have done here is create the basic HTML markup for our application.  Then we include AngularJS on the page and then create our Angular application and add a controller to it.  Let’s initialize our controller with some data and add a method to our scope that will add a new drummer to the list.  Put the following inside the controller function.


$scope.newDrummer = {};
$scope.drummers = [
    { firstName: 'Neil', lastName: 'Peart', alive: true },
    { firstName: 'John', lastName: 'Bonham', alive: false },
    { firstName: 'Keith', lastName: 'Moon', alive: false },
    { firstName: 'Buddy', lastName: 'Rich', alive: false },
    { firstName: 'Dave', lastName: 'Grohl', alive: true },
    { firstName: 'Ringo', lastName: 'Star', alive: true },
    { firstName: 'Mike', lastName: 'Portnoy', alive: true },
    { firstName: 'Lars', lastName: 'Ulrich', alive: true },
    { firstName: 'Stewart', lastName: 'Copeland', alive: true },
    { firstName: 'Travis', lastName: 'Barker', alive: true },
    { firstName: 'Chad', lastName: 'Smith', alive: true },
    { firstName: 'James', lastName: 'Sullivan', alive: false },
    { firstName: 'Tony', lastName: 'Williams', alive: false },
    { firstName: 'Luke', lastName: 'Holland', alive: true },
    { firstName: 'Matt', lastName: 'Greiner', alive: true },
];

$scope.addDrummer = function() {
    $scope.newDrummer.alive = $scope.newDrummer.alive === 'true';
    $scope.drummers.push($scope.newDrummer);
    $scope.newDrummer = {};
};

This code is pretty simple.  We are creating an object called “newDrummer” that we will populate using our form later.  We then create an array of drummer, each with a first name, last name, and whether they are alive or not.  Lastly, we create a function that will be run when our form is submitted that will add the drummer to the array and then clear it out.  The first line of the function simply compares the “alive” value to the string “true” and puts that boolean value in alive.  This is because our filter will look for the boolean true, but a select list will initially put the string “true” in our object.  This simply turns the string “true” or “false” into their boolean counterparts.

Now that we have our data, let’s get some of this showing in the browser.  Put the following in the template for the controller.

{% raw %}


<div id="drummer-lists">
    <ul>
        <li ng-repeat="drummer in drummers | filter: { alive: true }">

        </li>
    </ul>
    <ul>
        <li ng-repeat="drummer in drummers | filter: { alive: false }">

        </li>
    </ul>
</div>

{% endraw %}

This creates two unordered lists, one with all the drummers who are still alive and the other with those who are not.  We are easily able to filter them out using the “filter” filter.  The object we pass it shows what must be true in each object for it to be included in the output ng-repeat puts in our list.

Let’s add a form to the page so we can add a drummer to our list.  Put the following after our drummer lists.


<form ng-submit="addDrummer()">
    <h1>Add a drummer</h1>
    <label for="firstName">First Name</label>
    <input name="firstName" type="text" ng-model="newDrummer.firstName">
    <label for="lastName">Last Name</label>
    <input name="lastName" type="text" ng-model="newDrummer.lastName">
    <label for="alive">Is Alive?</label>
    <select name="alive" ng-model="newDrummer.alive">
        <option value="">Pick an option</option>
        <option value="no">False</option>
        <option value="yes">True</option>
    </select>
    <input type="submit" value="Add Drummer">
</form>

This is a simple form that will populate the fields in our newDrummer object on our $scope and then will fire our “addDrummer” function once the form has been submitted.  You will now be able to fill out the form, submit it, and see your drummer added to one of the lists.

Now, let’s say we wanted to add a counter to each of our lists.  We could manage all that in our controller by reducing our array to numbers to count the number of each type of drummer in our list, but that would be alot more code than is necessary.  Instead, we can manage this all in our views.  Change the lists to look like the following code.

{% raw %}


<div id="drummer-lists">
    <p>Number of awesome drummers still alive:  / </p>
    <ul>
        <li ng-repeat="drummer in alive = (drummers | filter: { alive: true })">

        </li>
    </ul>
    <p>Number of awesome drummers that have passed on:  / </p>
    <ul>
        <li ng-repeat="drummer in dead = (drummers | filter: { alive: false })">

        </li>
    </ul>
</div>

{% endraw %}

This is very similar to before.  However, notice we have instead used the filter on the drummers array and then saved that value in new array called “alive” and “dead.”  It still iterates through this object like before.  We can also use this object elsewhere in our view.  I have chosen to add a counter to show how many are in each list.  This is much nicer than handling it in the controller because it will automatically update when we add, change, or remove something in the drummers array.

Filters in Angular can be very powerful.  When used correctly, they can help keep the logic in your application organized and keep you controllers from being too big.  Make sure to leave us comment below to let us know how this has helped you!

Author

Facebook
Twitter
LinkedIn
Email
Originally Published: January 4, 2016

Subscribe To Our Newsletter

October 23, 2023
Originally published on January 4, 2016

Other Articles You Will Enjoy

How Does BigQuery Data Import for Google Analytics 4 Differ from Universal Analytics?

How Does BigQuery Data Import for Google Analytics 4 Differ from Universal Analytics?

All Google Analytics 4 (GA4) property owners can now enable ‌data export to BigQuery and start to utilize the raw event data collected on…

2-minute read
Leveraging Attribution Models in Google Analytics 4 to Improve Your Marketing Strategy: Tips and Best Practices

Leveraging Attribution Models in Google Analytics 4 to Improve Your Marketing Strategy: Tips and Best Practices

In the dynamic landscape of digital marketing, understanding the customer journey is crucial for optimizing strategies and maximizing ROI. Google Analytics 4 (GA4) introduces…

5-minute read
Is It Time to Upgrade? 4 Signs Your Organization Needs Google Analytics 4 360

Is It Time to Upgrade? 4 Signs Your Organization Needs Google Analytics 4 360

As VP of Partnerships at InfoTrust, I’ve had the opportunity to talk with hundreds of decision-makers about their interest in upgrading to Google Analytics…

4-minute read
Deploying Digital Analytics Changes at Scale for CPG and Multi-Brand Organizations

Deploying Digital Analytics Changes at Scale for CPG and Multi-Brand Organizations

The digital analytics industry is going through seismic shifts, and it is important for CPG organizations to stay abreast of the changes and stay…

5-minute read
How to Integrate Google Analytics 4 with BigQuery for Enhanced Data Analysis and Reporting

How to Integrate Google Analytics 4 with BigQuery for Enhanced Data Analysis and Reporting

Has your business found that its reporting needs require advanced analysis of your analytics data beyond what is practical in the Google Analytics 4…

4-minute read
Advanced Analysis Techniques in Google Analytics 4: How to Use AI-Powered Insights and Predictive Analytics for Effective Marketing

Advanced Analysis Techniques in Google Analytics 4: How to Use AI-Powered Insights and Predictive Analytics for Effective Marketing

AI-powered insights and predictive analytics are revolutionary tools reshaping the modern marketing landscape. These advanced analytics techniques, particularly prominent in Google Analytics 4 (GA4),…

8-minute read
What Is Consent Mode in Google Analytics 4 and How Does It Work? | A Beginner’s Guide

What Is Consent Mode in Google Analytics 4 and How Does It Work? | A Beginner’s Guide

Consent Mode in Google Analytics 4 (GA4) is a helpful tool for website owners to respect user privacy preferences when it comes to tracking…

3-minute read
Leveraging Custom Dimensions and Metrics in Google Analytics 4 for Content Performance Measurement: Best Practices and Real-World Examples

Leveraging Custom Dimensions and Metrics in Google Analytics 4 for Content Performance Measurement: Best Practices and Real-World Examples

In today’s digital landscape where content reigns supreme, understanding how your audience interacts with your content is paramount for success. For news and media…

5-minute read
App Install Attribution in Google Analytics 4: What You Need to Know

App Install Attribution in Google Analytics 4: What You Need to Know

App install attribution in Google Analytics for Firebase (GA4) is a feature that helps you understand how users discover and install your app. It…

6-minute read

Get Your Assessment

Thank you! We will be in touch with your results soon.
{{ field.placeholder }}
{{ option.name }}

Talk To Us

Talk To Us

Receive Book Updates

Fill out this form to receive email announcements about Crawl, Walk, Run: Advancing Analytics Maturity with Google Marketing Platform. This includes pre-sale dates, official publishing dates, and more.

Search InfoTrust

Leave Us A Review

Leave a review and let us know how we’re doing. Only actual clients, please.