SEI-Example
  • Introduction
  • About These Notes
  • Syllabus
  • Development Workflow
    • Installfest
      • Mac OSX
      • Linux
      • Git Configuration
      • Sublime Packages
    • Command Line
      • The Terminal
      • Filesystem Navigation
      • File Manipulation
      • Additional Topics
    • Intro to Git
      • Version Control
      • Local Git
      • Remote Git
      • Git Recipes
    • Group Collaboration
      • Git Workflows
      • Project Roles and Tools
    • VS Code Tips & Tricks
  • HTML/CSS
    • HTML
    • CSS Selectors
    • CSS Box Model and Positioning
      • Box Model
      • Display and Positioning
      • Flexbox
      • Grid
      • Flexbox & Grid Games
      • Floats and Clears
      • Additional Topics
    • Advanced CSS
      • Responsive Design
      • Pseudo-Classes/Elements
      • Vendor Prefixes
      • Custom Properties
      • Additional Topics
    • Bootstrap
    • CSS Frameworks
    • Accessibility
  • JavaScript
    • Primitives
    • Arrays
    • Objects
    • Control Flow
      • Boolean Expressions
      • Conditionals
      • Loops
      • Promises
    • Functions
      • Callbacks
      • Timing Functions
      • Iterators
    • DOM and Events
    • DOM Manipulation
    • HTML5 Canvas
    • How To Reduce Redundancy
    • (2019) JavaScript OOP
    • (2016) OOP with Classes
    • (1995) OOP with Prototypes
      • Constructors
      • Prototypes
    • Intro to TDD
    • Scoping
    • Inheritance
      • Prototypal Inheritance
      • Call, Apply, and other Functions
      • ES6 Inheritance
      • Resources
    • Custom Node Modules
    • Additional Topics
      • AJAX, Fetch, and Async/Await
      • AJAX w/JSON and Localstorage
        • AJAX w/JSON
        • Local Storage
      • Async module
      • Data Scraping
  • jQuery
    • Intro
      • DOM Manipulation
      • Reddit Practice
      • Styling
      • Events
    • Plugins
    • AJAX
  • APIs
    • Fetch
    • AJAX w/jQuery
    • AJAX w/Fetch
  • Databases
    • Intro to SQL
    • Advanced SQL
    • MongoDB
      • Intro to NoSQL
      • CRUD in MongoDB
      • Data Modeling
      • Intermediate Mongo
  • Node/Express
    • Node
      • Intro to Node
      • Node Modules
      • Node Package Manager (NPM)
    • Express
      • Intro to Express
        • Routes
        • Views
        • Templates
        • Layouts and Controllers
        • CRUD & REST
          • Get and Post
          • Put and Delete
      • APIs with Express (request)
      • APIs with Express (axios)
    • Sequelize
      • Terminology
      • Setup
      • Using Models
      • Seeding Data
      • Validations and Migrations
      • Resources
      • 1:M Relationships
      • N:M Relationships
    • Express Authentication
      • Research Components
      • Code Components
      • Auth in Theory
        • Sessions
        • Passwords
        • Middleware
        • Hooks
      • Auth in Practice
        • Create the User
        • User Signup
        • Sessions
        • User Login
        • Authorization and Flash messages
    • Testing with Mocha and Chai
    • Mongoose
      • Mongoose Associations
    • JSON Web Tokens
      • Codealong
    • Additional Topics
      • oAuth
      • Geocoding with Mapbox
      • Geocoding and Google Maps
      • Cloudinary
      • Websockets with Socket.io
      • SASS
  • Ruby
    • Intro to Ruby
    • Ruby Exercises
    • Ruby Classes
    • Ruby Testing with Rspec
    • Ruby Inheritance
    • Ruby Data Scraping
  • Ruby on Rails
    • Intro to Rails
    • APIs with Rails
    • Asset Pipeline
    • Rails Auth and 1-M
      • Auth Components
    • Rails N:M
    • ActiveRecord Polymorphism
    • Additional Topics
      • oAuth
      • SASS
      • Rails Mailers
      • Cloudinary
      • Jekyll
  • React (Updated 2019)
    • ES6+/ESNext
      • Const and Let
      • Arrow Functions
      • Object Literals and String Interpolation
      • ES6 Recap
      • ES6 Activity
    • Intro to React
      • Create React App
      • Components and JSX
      • Virtual DOM
      • Props
      • Dino Blog Activity
      • Nested Components
      • Lab: LotR
    • React State
      • Code-Along: Mood Points
      • Code-Along: Edit Dino Blog
      • Lab: Simple Calc
      • Lifting State
    • React Router
      • Browser History/SPAs
      • React Router (lesson and full codealong)
      • Router Lab
    • Fetch and APIs
      • APIs with Fetch and Axios
      • Fetch the Weather
    • React Hooks
    • React LifeCycle
      • Lab: Component LifeCycle
    • React Deployment
    • Additional Topics
      • React Frameworks
        • Material UI Theming
      • Typescript
        • More Types and Syntax
        • Tsconfig and Declaration Files
        • Generics with Linked List
      • Redux
      • TypeScript
      • Context API
      • React Native
  • Meteor
  • Deployment and Config
    • Deploy - Github Pages
    • Deploy - Node/Sequelize
    • Deploy - Node/MongoDB
    • Deploy React
    • Deploy - Rails
      • Foreman (Environment Variables)
    • Deploy - AWS Elastic Beanstalk
    • Deploy - S3 Static Sites
    • Deploy - Django
    • Deploy - Flask
  • Data Structures and Algorithms
    • Recursion
    • Problem Solving - Array Flatten
    • Binary Search
    • Algorithm Complexity
    • Stacks and Queues
    • Bracket Matching
    • Ruby Linked Lists
      • Sample Code
      • Beginner Exercises
      • Advanced Exercises
    • JS Linked Lists
      • Sample Code
      • Beginner Exercises
      • Beginner Solutions
    • Hash Tables
    • Intro to Sorting
    • Insertion Sort
    • Bucket Sort
    • Bubble Sort
    • Merge Sort
    • Quick Sort
    • Heap Sort
    • Sorting Wrapup
    • Hashmaps
    • Trees and Other Topics
  • Python
    • Python Installation
    • Intro to Python
    • Python Lists
    • Python Loops
    • Python Dictionaries
    • Python Sets and Tuples
    • Python Cheatsheet
    • Python Functions
    • Python Classes
    • Python Class Inheritance
    • Intro to Flask
    • Intro to SQLAlchemy
      • Flask and SQLAlchemy
    • Using PyMongo
    • Intro to Django
    • CatCollector CodeAlong
      • URLs, Views, Templates
      • Models, Migrations
      • Model Form CRUD
      • One-to-Many Relations
      • Many-to-Many Relations
      • Django Auth
    • Django Cheatsheet
    • Django Auth
    • Django Polls App Tutorial
    • Django School Tool Tutorial
    • Django 1:M Relationships
    • Custom Admin Views
    • Data Structures and Algorithms
      • Recursion
      • Binary Search
      • Stacks and Queues
      • Linked Lists
      • Binary Trees
      • Bubble Sort
      • TensorFlow & Neural Networks
    • Adjacent Topics
      • Raspberry Pi
      • Scripting
  • Assorted Topics
    • History of Computer Science
    • Regular Expressions
    • Intro to WDI (Course Info)
    • Being Successful in WDI
    • Internet Fundamentals
      • Internet Lab
    • User Stories and Wireframing
      • Wireframing Exercise: Build an Idea
    • Post WDI
      • Learning Resources
      • Deliverables -> Portfolio
      • FAQ
  • Projects
    • Project 1
    • Project 2
    • Project 3
      • Project 3 Pitch Guidelines
    • Project 4
    • Past Projects
      • Project 1
      • Project 2
      • Project 3
      • Project 4
      • Portfolios
    • Post Project 2
    • MEAN Hackathon
      • Part 1: APIs
      • Part 2: Angular
    • Portfolio
  • Web Development Trends
  • Resources
    • APIs and Data
    • Tech Websites
    • PostgreSQL Cheat Sheet
    • Sequelize Cheat Sheet
    • Database Administration
  • Archived Section
    • (Archived) ReactJS
      • Intro to React
        • Todo List Codealong
        • Additional Topics
      • Deploy React
      • React with Gulp and Browserify
        • Setting up Gulp
        • Additional Gulp Tasks
      • React Router
        • OMDB Router
        • OMDB Search
        • Additional Resources
      • React Animations
        • CSS Animations
    • AngularJS
      • Intro to AngularJS
        • Components and SPA
        • Create an Angular App
      • Angular Directives and Filters
      • Angular Animation
      • Angular Bootstrap Directives
        • Bootstrap Modals
      • Angular $http
      • Angular Services
        • Service Recipes
        • ngResource
        • Star Wars Codealong
      • Angular Routing
      • Angular + Express
      • Angular Authentication
        • Additional Topics
      • Angular Components
      • Angular Custom Filters
      • Angular Custom Directives
Powered by GitBook
On this page
  • Objectives
  • Review of Filters
  • Chaining filters
  • Custom Filters
  • Complete filter example
  • Exercises
  • nth
  1. Archived Section
  2. AngularJS

Angular Custom Filters

Objectives

  • Review the concept of filters in Angular

  • Create a custom filter and utilize it in an app

Review of Filters

Angular uses the concept of filters to easily process data before output. Filters can work on any type of data (strings, numbers, arrays, etc). There are a bunch of built-in filters and we can easily create our own.

Basic Filter Example

{{myVar | lowercase}}

Outputs the value of myVar in to the lowercase filter which outputs the string as lowercase.

Filter options

Some filters also take in optional parameters. Angular uses colons (:) to separate arguments for filters.

Filter Arguments Example

//in controller
$scope.someNumber = 12345;


//in view
{{someNumber | currency}}
// Outputs: '$12,345.00'

{{someNumber | currency : '£'}}
// Outputs: '£12,345.00'

{{someNumber | currency : '£' : 4}}
// Outputs: '£12,345.0000'

Chaining filters

Filters can be chained together just like terminal commands. The output of each filter will feed into the next filter.

In this example we'll use a filter called limitTo which limits the length of a string or array.

Example

//in controller
$scope.myWords = 'My String With Caps';


//in view
{{myWords | lowercase}}
//outputs: 'my string with caps'

{{myWords | limitTo : 5}}
//outputs: 'My St'

{{myWords | lowercase | limitTo : 5}}
//outputs: 'my st'

Custom Filters

Creating a custom filter is fairly simple, but the syntax is a little foreign at first. Let's create a filter called reverse that takes a word and prints it in reverse.

Example

myApp.filter('reverse', function() {
  return function(input, preserveWords) {
    //format word and return here
  }
});

A filter is created by using the filter method, and like the other angular methods, the first parameter is the name of the filter we want to create. The second parameter is a function that returns another function.

This inner function is the actual filter that is triggered using the same syntax as the built-in filters.

The first parameter of the inner function is the actual data that was piped in to the filter. Every subsequent parameter come from things separated by colons (again like in the built-in filters).

Usage Example

{{someVar | reverse : true}}

This would trigger the inner function and set input to the value of someVar and preserveWords to true. Additional, parameters can be added in the same fashion.

Complete filter example

The below filter will take in a word and output it reversed. If preserveWords is set to true, it will keep the words intact.

Custom Filter

myApp.filter('reverse', function() {
  var reverseWord = function(word) {
    return word.split('').reverse().join('');
  }

  return function(input, preserveWords) {
    if(!input) return input;
    if(preserveWords) {
      return input.split(' ').map(function(word){
        return reverseWord(word);
      }).join(' ');
    } else {
      return reverseWord(input);
    }
  }
});

Usage Example

//in controller
$scope.someText = 'This is some text';


//in view
{{someText | reverse}}
//output: 'txet emos si sihT'

{{someText | reverse : true}}
//output: 'sihT si emos txet'

Exercises

nth

Create a filter called 'nth' that accepts a number and adds the proper suffix to it, like 1st, 2nd, 3rd, 4th and so on. Zero should show as 0th.

Sample input:

<ul>
  <li ng-repeat="i in [1,2,3,4]">
    {{i | nth}} place
  </li>
</ul>

Sample output:

1st place
2nd place
3rd place
4th place

pluralize

Assume you have an array of objects. Create a filter called 'pluralize' that accepts accepts a list length as an input and accepts two other parameters:

  • length - a number representing a quantity

  • singular - a string to show if the length is 1

  • plural - a string to show if the length is not 1

The filter should return the singular string if the input length is exactly equal to one. Otherwise, it should return the plural string.

The plural string is an optional parameter. Detect if it is passed to the filter. If plural is not passed to the filter then append the letter "s" to the singular string.

<div class="inbox">
  {{planes.length}} new {{ planes.length | pluralize: "message"}}
</div>

<div class="zoo">
  {{octopus.length}} {{ planes.length | pluralize: "octupus":"octopi"}} spotted today.
</div>

The filter should output the following text to the page for different input:

0 new messages
1 new message
12 new messages
0 octopi spotted today.
1 octopus spotted today.
23 octopi spotted today.

filesize

Create a filter called filesize that accepts a number representing the number of kilobytes in a file and returns a string with a human-readable size description in the following units:

  • bytes

  • KB - kilobytes (1024 bytes)

  • MB - megabytes (1024 kilobytes)

  • GB - gigabytes (1024 megabytes)

<ul ng-repeat="bytes in [123, 1024, 1536, 1048576, 1310720]">
  {{ bytes | filesize: 2}}
</ul>

The filter should output the following list on the page:

123 KB
1.00 MB
1.50 MB
1.00 GB
1.25 GB

primes

Create filter called primes that accepts a list of numbers and returns a new list containing only prime numbers:

<ul ng-repeat="num in [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17] | primes">
  <li>{{num}}</li>
</ul>

The filter should output the following list on the page:

2
3
5
7
11
13
17

ago

Create a filter called ago that accepts a timestamp string and returns a string representing how long ago the timestamp occurred.

The filter should support time units of years, months, days, hours, seconds and anything occuring less than 3 seconds ago should just say 'moments ago.'

Notice the sample output properly pluralizes "1 year ago" and "2 years ago." It's possible to use filters outside of views! Search the internet to find out how to call one filter from inside another filter.

Use the Date object to perform date calculations. MDN has great documentation about what methods are available on instances of the Date object. (Note: be sure to notice that the getYear() method was deprecated because of the Y2K bug!)

var then = new Date("2010-12-05T08:03:22Z");
var now = new Date("2010-01-11T08:01:57Z");

var years = now.getFullYear() - then.getFullYear()
// ... and so on

Here's some sample input:

{{ 'May 27 2014 00:17:00 GMT-0700' | ago}}
{{ 'Sep 27 2015 00:17:00 GMT-0700' | ago}}
{{ 'Feb 27 2016 00:17:00 GMT-0700' | ago}}
{{ 'May 22 2016 00:17:00 GMT-0700' | ago}}
{{ 'May 26 2016 18:17:00 GMT-0700' | ago}}
{{ 'May 27 2016 08:17:00 GMT-0700' | ago}}
{{ 'May 27 2016 09:30:00 GMT-0700' | ago}}
{{ (new Date().toString()) | ago}}

Here's some sample output. Beware, time is fickle and your actual results may vary:

2 years ago
1 year ago
5 days ago
23 hours ago
17 minutes ago
3 seconds ago
moments ago
PreviousAngular ComponentsNextAngular Custom Directives

Last updated 3 years ago

Each filter has it's own set of options. See the for more details.

More info:

The filter should accept an optional parameter precision that defaults to 2 that represents how many digits to show after the decimal place if the filesize if larger than one megabyte. Refer to for details.

full list of built-in filters
Angular Docs - Filters
MDN toFixed() documentation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getYear