sslepian
sslepian

Reputation: 1921

Angular "Unknown provider" error when using $filter in directive

I've got a directive that needs to use angular's $filter in the code. However, when trying to use it, I'm getting an error:

[$injector:unpr] Unknown provider: FilterProvider <- Filter

Here's a minimal example of what's causing the error: http://jsfiddle.net/5tLtj3nh/

I'm stumped trying to figure out what I'm doing wrong.

Upvotes: 3

Views: 14758

Answers (3)

CredibleAshok
CredibleAshok

Reputation: 73

for working plnkr

http://plnkr.co/edit/US6xE4h0gD5CEYV0aMDf?p=preview

check how your angular environment is setup. Follow Steps:

check if your Index.html has loaded script.

<script src="scripts/angular-filter.js"></script>

check if $filter is used in your controller

    (function () {
    'use strict';
    var controllerId = 'controllerName';
    angular.module('myApp')
    .controller(controllerId, ['$rootScope', '$scope', '$timeout', 'security', '$filter', functionName]);
    function functionName($rootScope, $scope, $timeout, security, $filter) {
        // your controller code.
    }})();

You html page is using FilterBy

    <tr ng-repeat="row in tableList | filterBy: ['col1','col2','col3'] : vm.listFilter">
        <td class="text-left">{{row.col1}}</td>
        <td class="text-left">{{row.col2}}</td>
        <td class="text-left">{{row.col3}}</td>
    </tr>

Don't forget to include dependency while loading angular

    var app = angular.module('app', [
    'common',           // These are just example, can be anything
    'common.bootstrap', 
    'security',         
    'nsPopover', 'angular.filter'
    ]);

Upvotes: 1

runTarm
runTarm

Reputation: 11547

You are using the $filter service incorrectly.

You have to get a filter from $filter service first like this:

var filterFilter = $filter('filter');
filterFilter([], 'query');

or a one liner:

$filter('filter')([], 'query');

In case you are confused, the 'filter' filter is one of the build-in filters of angularjs.

There are many more, see: https://docs.angularjs.org/api/ng/filter

  • currency
  • date
  • filter
  • json
  • limitTo
  • lowercase
  • number
  • orderBy
  • uppercase

Tip: You could also inject an individual filter to use like this:

app.directive('testDirective', ['filterFilter', function(filterFilter) {
    return {
        restrict: 'E',
        template: '<div>testDirective</div>',
        link: function(scope, elem, attrs) {
            filterFilter([], 'query');
        }
    }
}]);

Upvotes: 5

Beyers
Beyers

Reputation: 9118

As mentioned in the comments, your syntax is wrong. To use the filter $filter the syntax as per the documentation is:

$filter('filter')(array, expression, comparator)

Assuming you want to filter based on the query string you'll need:

$filter('filter')([], 'query')

Upvotes: 1

Related Questions