This article shows how to check if a filter exists in AngularJS
In some cases it may be required to check if a filter is defined in your AngularJS application.
This might especially be the case when writing reusable components.
Initial setup
First let’s create a very simple AngularJS application with a filter:
1 2 3 4 5 6 7 8 9 10 11 12 |
var app = angular.module('resolvethis', []); app.controller('MainCtrl', function($scope) { $scope.welcome= 'Hello World'; }); //The filter: app.filter('upper', function () { return function (input) { input.toUpperCase(); }; }); |
The check
Now that we have our test application, we can check if the filter ‘upper’ exists:
1 2 3 4 5 6 7 |
app.config(function($injector){ if($injector.has('$upper')){ console.log('Yep, we got the filter!'); } else { console.log('We are missing the filter, maybe create a mock here?'); } }); |
Beyond the concept
We could use this technique to poly-fill missing functionality which is required by one of our pluggable directives or services. A fully functional example can be found here on Plunker.