0

I have defined my own custom filter, in order to search through posts in an angular.js web application:

app.filter('myfilter', function() {
return function(postList, term) {
  var out = [];

  if(!postList) return out;    
  if(!term) return postList;

  var i;
  for(i = 0; i < postList.length; i++){
    if(postList[i].title.indexOf(term) >=0){
        out.push(postList[i]);
    }

    if($scope.isContentFilterOn.checked){
        if(postList[i].text.indexOf(term) >=0){
                out.push(postList[i]);
            }
        }
    }
    }
    return out;
}
});

Of course the above will not work, because I can't access scope variables, and simply passing the $scope doesn't work as well. How could I do it - is there any simple and fast way?

Edit: source http://plnkr.co/edit/G9BFBTaKdUmki8MJegrn?p=catalogue

Michał Szydłowski
  • 3,261
  • 5
  • 33
  • 55
  • possible duplicate question: http://stackoverflow.com/questions/17596246/access-scope-variables-from-a-filter-in-angularjs – Patrick Motard May 18 '15 at 21:58
  • This is what services were made for. Create an api to hold the state of the filter and let the controller and directive use them both – richbai90 May 18 '15 at 22:42

1 Answers1

0

You can pass any number of scope members directly to the filter (separated by a colon)...

myfilter:filterTerm:isContentFilterOn

Update the filter method signature...

function(postList, term, isContentFilterOn) {

Then use it how you wish...

 if (isContentFilterOn) { 

Oh and don't forget you may need to define isContentFilterOn in the scope as false to begin with so it's available to the filter right away...

$scope.isContentFilterOn = false;

Updated Plunker here to show what I mean...

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

brenters
  • 46
  • 3
  • Also fyi you don't use **isContentFilterOn.checked** just **isContentFilterOn** (as the ng-model will resolve to true or false because a checkbox element can only have 2 values (checked/unchecked i.e. true/false). – brenters May 18 '15 at 23:30