Reputation:
I need to alter how a filter works based on a setting in my controller. Can I access controller vars from my filter? Do I add the var on to the filter parameter list in the template?
Thanks in advance.
Upvotes: 0
Views: 2083
Reputation: 18523
you should pass whatever you need from your controller into the filter function. e.g.:
JS
app.filter('myFilter', function () {
return function(input, myParam) {
if (myParam) {
return input;
} else {
return [];
}
};
}
HTML
<div>{{myCtrl.someList | myFilter:myCtrl.someSetting}}</div>
Upvotes: 1
Reputation: 48211
If you are invoking the filter in the view, you can add the var in the filter parameter list.
Any vars appended to the filter parameter list in the view, will be appended to the filter function arguments (after the filtered object).
E.g.:
The filter:
.filter('doSomeFiltering', function () {
return function (someObj, myVar1, myVar2) {
...
};
});
The view:
{{thisWillBeSomeObj | doSomeFiltering:thisWillBeMyVar1:thisWillBeMyVar2}}
The controller:
$scope.thisWillBeSomeObj = ...;
$scope.thisWillBeMyVar1 = ...;
$scope.thisWillBeMyVar2 = ...;
See, also, this short demo.
Upvotes: 1