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

前端 未结 4 2152
温柔的废话
温柔的废话 2021-02-20 03:15

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,

4条回答
  •  情书的邮戳
    2021-02-20 03:56

    You don't need to inject the filter itself.

    This code...

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

    Should be

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

    And inside CourseCtrl you should use your filter as you normally do.

    Injecting the module 'equiclass.filters' into your module 'equiclass.controllers' is enough.

    I had a similar issue and made a post about it on my blog.

    --Edit

    As n00dl3 mentions below the tricky part is how the auto-naming convention works in Angular. If you name your filter specialNumberFilter then when you inject it you need to refer to it as specialNumberFilterFilter. This allows you to use the filter as a function, which is what it is.

    // In a controller vm.data = specialNumberFilterFilter(vm.data, 'a');

    But I believe you can also use the filter without injecting it into a controller if it is used in a string expression that is being evaluated by, say, a watch because this would be the same as the scenario when you are using it in a template.

    // Inside a watch - no controller injection required `$scope.$watch('vm.data | specialNumberFilter', function(new, old) { ... })`

提交回复
热议问题