Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass $filter inside link function of angular directive

I need $filter inside the link function of angular directive but there is no way to pass $filter as a parameter to link function.

app.directive('myDirective', function($compile) {
  return {
    restrict: 'A',
    scope: {
      ngModel: '=',
    },
    require: 'ngModel',
    link: function($scope, elem, attr, ctrl) {

    }
  };
});

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

How to access the $filter inside link function?

like image 321
Vivek Avatar asked Nov 03 '15 11:11

Vivek


2 Answers

Just inject it into your actual directive function, and then it can be used throughout your directive (including your link function).

app.directive('myDirective', function($compile, $filter){
    return {
        restrict: 'A',
        scope: {
            ngModel: '=',
        },
        require: 'ngModel',
        link: function($scope, elem, attr, ctrl) {
            // call $filter here as you wish

        }
    };
});

Just think of the link function as a private directive function that doesn't deal directly with angular's injection system. By injecting in the main directive function you are essentially saying that all internal functions can use it.

like image 72
Matt Way Avatar answered Oct 12 '22 23:10

Matt Way


you need to inject the $filter dependency , all your custom services/factory and in-built angular providers ($timeout,$filter) should be inject as below

  app.directive('myDirective', ['$compile','$filter',function($compile,$filter) {
  return {
    restrict: 'A',
    scope: {
      ngModel: '=',
    },
    require: 'ngModel',
    link: function($scope, elem, attr, ctrl) {
      console.log($filter);
    }
  };
}]);

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

like image 34
Shushanth Pallegar Avatar answered Oct 13 '22 00:10

Shushanth Pallegar