Using an AngularJS Filter in HTML Vs. Using It In JavaScript

Datetime:2016-08-23 02:35:13          Topic: AngularJS  HTML           Share

I recently found myself Googling "how to use an AngularJS filter from JavaScript controller" and found the answer so I decided to write a blog post to help burn the solution into my brain. :)

The Situation

I was working on an AngularJS project that had a the text "APRIL" hardcoded into a div like so:

<div>
  APRIL
</div>

My job was to replace this with the controller variable  currentMonth and make sure that the text always appears in all caps, regardless of the case of the string stored in the variable. Sounds like a great opportunity for, dun da da da dun dun dun daaaaaaaaannn: filters! 

HTML Filter Solution

Since the  uppercase  filter in built into Angular, we can use use it right in our HTML markup like this:

<div>
  {{ ctrl.currentMonth | uppercase }}
</div>

This is a nice syntax and looks quite lovely, but it's actually not as optimized as the method below.

JavaScript Filter Solution

During my time studying AngularJS at NYCDA, my professor showed us how javascript filters actually performed better than putting them in the markup. You can actually inject the $filter service into any of your Angular components, services, etc. and apply any of your filters to some piece of data. Here is an example of how you could use the filter service from inside a controller:

self.calendarMonth = $filter('uppercase')(self.calendarMonth);

And as another optimization we can replace the interpolation curly braces with ng-bind like this:

<div>
 <span ng-bind="ctrl.currentMonth"></span>
</div>




About List