2

I want to check if an array contains a string and followup on it. indexOf() is not an option because it is strict.

Plunker Here

You can find the described problem in the app.filter('myOtherFilter', function()

app.filter('myOtherFilter', function() {
    return function(data, values) {
      var vs = [];
      angular.forEach(values, function(item){
        if(!!item.truth){
          vs.push(item.value);
        }
      });

      if(vs.length === 0) return data;

      var result = [];
      angular.forEach(data, function(item){
        if(vs.toString().search(item.name) >= 0) {
          result.push(item);
        }
      });
      return result;
    }
  });

Is this correct and is the error somewhere else?

2 Answers 2

2
angular.forEach(data, function(item){   
    for(var i = 0; i < vs.length; i++){
        if(item.name.search(vs[i]) >= 0) {
            result.push(item);
        }
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

You could always extract the Angular filter filter, which takes an array but will handle the different types properly. Here is the general idea:

app.filter('filter', function($filter) {
    var filterFilter = $filter('filter');

    function find(item, query) {
        return filterFilter([item], query).length > 0;
    }

    return function(data, values) {
        var result = [];

        angular.forEach(data, function(item) {
            for(var i = 0; i < values.length; i++) {
                if(find(item, values[i])) {
                    result.push(item);
                    break;
                }
            }
        });

        return result;
    };
}

});

You'll have to change the structure of the data you are passing in. Pass in a list of values, not a list of {truth: true}. This solution allows you to leverage the existing power of the Angular "filter" filter.

1 Comment

do you have a plunk/fiddle of that in action? I cant really wrap my head around that idea

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.