admin管理员组

文章数量:1415673

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?

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?

Share Improve this question asked Sep 5, 2013 at 7:40 DennisKoDennisKo 2732 gold badges6 silver badges19 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2
angular.forEach(data, function(item){   
    for(var i = 0; i < vs.length; i++){
        if(item.name.search(vs[i]) >= 0) {
            result.push(item);
        }
    }
});

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.

本文标签: Search array for string (javascriptangularjs)Stack Overflow