Angular - Using Filters in Controllers

Angular provides us with several filters which are useful formatting values inside our templates in a declarative way. For example, we can use the number filter to round a given value to a specified number of decimals.

<span>Rounded number: {{ value | number : 2 }}</span>

These filters are always available to us inside templates - but what if you want to use a filter inside a controller? This is actually very easy to do - you simply need to inject the $filter service into your controller.

app.controller "ExampleCtrl", ($scope, $filter) ->
  this.formatNumber = (value, decimals) ->
    $filter("number")(value, decimals)

Of course, you can create your own filters in angular and use them in exactly the same way.

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