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?

4

2 回答 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);
        }
    }
});
于 2013-09-05T07:56:50.727 回答
0

您总是可以提取 Angularfilter过滤器,它接受一个数组,但会正确处理不同的类型。这是一般的想法:

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;
    };
}

});

您必须更改传入数据的结构。传入值列表,而不是{truth: true}. 此解决方案允许您利用 Angular“过滤器”过滤器的现有功能。

于 2013-09-05T10:10:59.597 回答