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

2
  • possible duplicate question: stackoverflow.com/questions/17596246/… Commented May 18, 2015 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 Commented May 18, 2015 at 22:42

1 Answer 1

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

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

1 Comment

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).

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.