Reputation: 23317
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.
Upvotes: 1
Views: 6472
Reputation: 3497
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>
Upvotes: 2
Reputation: 1941
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.
Upvotes: 6