AngularJS 1.x custom filter can't be injected, unknown provider

stinaq picture stinaq · Apr 16, 2014 · Viewed 35.4k times · Source

I'm trying to create a custom filter, but when I try to inject it into my controller, I get an 'Unknown provider' error. I have checked and double checked all the references, but I can't see what's wrong.

I know that the file is referenced in my index.html correctly, it is loaded and can be found by the inspector. This is the code I have:

In my app.js:

angular.module('equiclass', ['equiclass.controllers',
                         'equiclass.services',
                         'ngRoute'])
.config(function ($routeProvider) {
$routeProvider
  .when('/courses', {
    templateUrl: 'views/courses.html',
    controller: 'CourseCtrl'
  // And some other stuff with routes
});

angular.module('equiclass.controllers', ['equiclass.services', 'equiclass.filters']);
angular.module('equiclass.services', []);
angular.module('equiclass.filters', []);

My filter:

angular.module('equiclass.filters')
  .filter('testFilter', function() {
    return function(input) {
      return undefined;
    };
});

And the controller:

angular.module('equiclass.controllers')
  .controller('CourseCtrl', function ($scope, testFilter) {

  });

Of course this is quite simplified, but it just doesn't work, and I can't see why. I have made several services and they all work and play along nicely.

Answer

BKM picture BKM · Apr 16, 2014

If you want to use filter inside a controller you have to inject $filter attribute to your controller and can access it like

$filter('filtername');

You can use like

function myCtrl($scope, $filter)
{
    $filter('filtername')(arg1,arg2);
}