user154759
user154759

Reputation:

How can I access a variable in $scope from inside a filter function?

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

Answers (2)

rob
rob

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

gkalpak
gkalpak

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

Related Questions