Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 590
stinaq Avatar asked Apr 16 '14 09:04

stinaq


2 Answers

According to Angular's documentation :

if you want to use your filter in a template

then you just need to inject it in your module and then use it like this {{ expression | filter }} or {{ expression | filter:argument1:argument2:... }} .

doc

if you want to use your filter in a controller, directive, and stuffs :

inject a dependency with the name <filterName>Filter, like this :

controller('MyController', ['filterFilter', function(filterFilter) {}]);

doc

so for this particular case :

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

  });
like image 117
n00dl3 Avatar answered Nov 13 '22 12:11

n00dl3


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);
}
like image 37
BKM Avatar answered Nov 13 '22 10:11

BKM