Create Some Filters With Angular

I continue again with angular. I’m working on a new project with this framework and it’s really pleasant to use it. After directives and services today I will speak about filters.

First, what is a filter ?

A filter is something which will transform your data. One good example is the use of the filter ‘filter’ which will search in an array all elements which contains a part of the search. Filter is not limited to array, it is just an input, some parameters and you process your input to have a result so you can apply a filter on a string element or number or whatever. Perhaps you already try to display a date as string. With angular there is already a filter for this and you can simply write.

1
myDate | date:'yyyy-MM-dd'

Let explain this a bit.

  • myDate is the data you want to process.
  • | is the instruction to say to angular I want to use a filter
  • date is the filter I want to use
  • : the separator to give some parameters to my filter
  • 'yyyy-MM-dd' the format of the date I want

Ok now everything is understood (I hope), we can create a new filter. I will take a simple case like just truncate a text. I would like to be able to truncate a long text with a filter. So my goal is to write this.

1
myLongText | truncate:100:'...'

In this instruction I will truncate myLongText to have 100 characters and finishing with ‘…’

filter/truncate.coffee
1
2
3
4
5
App = angular.module "app", []
App.filter 'truncate', ->
  (text, length, end) ->
    return text if not text or text.length <= length
    text.substring(0, length - end.length) + end
filter/truncate.js
1
2
3
4
5
6
7
8
9
10
11
12
var App;

App = angular.module("app", []);

App.filter('truncate', function() {
  return function(text, length, end) {
    if (!text || text.length <= length) {
      return text;
    }
    return text.substring(0, length - end.length) + end;
  };
});
Toggle coffeescript/javascript

That’s all !!

I just have to create a filter and return a function with my data as first argument then all the other arguments I want and this function will return the data after processing.

This is a simple case but a filter shouldn’t be complicated. Most of filters should have only 10 lines maximum but it can be really easy to read your code after and to find problems. So if you are using Angular, use and re-use a lot filters ;)

See the Pen iwAeG by Anthony (@antho1404) on CodePen

Comments

Copyright © 2014 - Anthony Estebe -