1

I would like to pass w filter as a param to a custom directive in my app. I would like to do something like:

Usage in application:

<my-directive data='dataVariable' dataFilter='numericFilter: 123'/>

Directive template:

<span> {{ data | dataFilter }} </span>

Directive:

...
scope: {
  data: '=',
  dataFilter: '@'
}
...

When I do it as shwon above I get error related to syntax (: is not recognized), dependency injection (filter is not found) or the filter simply does nothing.

2
  • Your dataFilter attribute should be data-filter. And how does dataFilter attribute work within the directive? Show the contents of your my-directive Commented Oct 29, 2014 at 12:43
  • dataFilter is not used inside the directive code. It is only needed to format HTML output. Commented Oct 29, 2014 at 12:44

2 Answers 2

6

You can dynamically get the filter you want by using the filter service:

angular.module('app').directive('myDir', ['$filter', function($filter) { 
....
     link: function($scope, $el, $attr) {
          var desiredFilter = $filter($attr['dataFilter']);
         //desiredFilter is now a function that will run the filter passed, it will throw exception if filter is not found
      }
 }

I hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

2

You could build up your expression in your compile function based off of your attributes. However, I would recommend using $filter as suggested by @PinhasHouri.

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

<!DOCTYPE html>
<html>

  <head>
    <script data-require="angular.js@*" data-semver="1.3.0" src="//code.angularjs.org/1.3.0/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <h1>Hello Plunker!</h1>
    <div apply-filter 
         filter-data="Hello" 
         filter-expr="append:'C'"></div>

    <script>
      var app  = angular.module("app",[]);

      app.directive("applyFilter",function(){
        return{
          filterExpr: "@",
          filterData: "@",
          compile: function(element,attrs){
            element.append("{{'" + attrs.filterData + "'|" +  attrs.filterExpr + "}}");
          }
        }
      });

      app.filter("append",function(){
        return function(v,p){
          return v + p;
        }
      });

      angular.bootstrap(document,["app"]);
    </script>
  </body>

</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.