Writing Custom Filters With AngularJS

Angular provides us with several filters which are useful formatting values inside our templates in a declarative way. The built-in filters are fairly useful, but the real power from filters comes from being able to write custom filters.

For example, we might want to write a pluralize filter, that works similar to the pluralize function in Rails.

Writing a custom filter is very simple - we simply call the filter function and return another custom function. This function takes at least one parameter and returns a single value. All filters can take additional parameters which can further enhance their behavior.

In this case I am going to accept two parameters - the count and the text to be pluralized. The first parameter will be the value the filter is applied to and additional parameters will be specified as colon-separated values.

For example, in this template the first parameter will be 5 and the second parameter will be the string ‘apple’.

<span>{{ 5 | pluralize : 'apple' }}</span>

Here is what the actual filter looks like:

app.filter "pluralize", ->
  (count, text) ->
    switch count
      when 1
        "#{count} #{text}"
        "#{count} #{text}s"

You can find the entire example on Plunker. Happy coding.