What is the best practice for using AngularJS filters in a controller/service?
I've seen both of the following methods to use a filter in a controller/service:
- $filter('myFilter')('myStuffToFilter', myFilterArgument)
- myFilterFilter('myStuffToFilter', myFilterArgument)
They work equally well. Which method constitutes best practice?
While this is not a ground-breaking issue, I believe there is a difference and it's worth sharing (as did pkozlowski.opensource in his answer to a related question). Option 2 is better for the following reasons:
- Cleaner syntax: It's a little cleaner, more straight forward and avoids the sequential parentheses syntax which is less common.
- Provided solution: The myFilterFilter object is not available for code injection by accident. The AngularJS creates these <filtername>Filter objects for all filters (pre-defined and custom) and makes them available to the injector.
- Documented solution: The AngularJS documentation recommends this solution in their documentation here.