使用angularjs过滤搜索结果

时间:2014-05-29 12:49:55

标签: angularjs search angularjs-directive filtering angularjs-service

我正在尝试使用angularjs构建搜索页面。我需要提供一些字段(复选框,广播,年龄范围等)作为搜索结果的过滤器。对于这个演示,我只关注复选框。我在下面的plunker列表中给出了一个演示代码

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

所以基本上,在上面的页面中,当用户选择“黄色”时,“结果1”的字段“显示”应该变为假。并且如果用户进一步选择“圆圈”,那么“结果2”的字段“显示”应该是假的。用户可以选择多种颜色或形状。

虽然我没有写过冗长的代码,但下面几乎是我想的:

whenever there is user action on filters{ //select or deselect
   for each result{ //"result 1", "result 2", "result 3"
      result.show=true

      //The below condition is m:n check and hence is a nested for loop.
      if none of the selected colors match the colors in the result 
         result.show=false

      //The below condition can be achieved using a single for loop
      if none of the selected shapes match the shape of the result
         result.show=false
   }
}

我想知道我可以参考设计上述功能的任何设计模式。如果在angularjs中有任何简单的替代方案来实现上述目的。

编辑:实际上我想隐藏与过滤条件不匹配的结果。我用“show”字段来演示这个例子。

1 个答案:

答案 0 :(得分:2)

这就是你要找的东西?

让HTML中的<div ng-repeat="result in results">等于<div ng-repeat="result in results | filter:searchFn">

这就是js。

var sampleFilter = angular.module('sampleFilter', []);

sampleFilter.service('lookups',function(){
    var colors = [
        {"id":1, "name":"Red"},
        {"id":2, "name":"Green"},
        {"id":3, "name":"Yellow"}
    ];
    var shapes = [
        {"id":1, "name":"Square"},
        {"id":2, "name":"Rectangle"},
        {"id":3, "name":"Circle"}
    ];
    this.colors = function(){
        return colors;
    }
    this.shapes = function(){
        return shapes;
    }
});

sampleFilter.service('search',function(){
    var results = [
        {"id":1, "colors":[1,2], "shape":2, "show":true},
        {"id":2, "colors":[1,3], "shape":1, "show":true},
        {"id":3, "colors":[2,3], "shape":3, "show":true}
    ];
    this.results = function(){
        return results;
    }
});

sampleFilter.controller('FilterController',['$scope', 'lookups', 'search', function($scope, lookups, search){
    $scope.colors = lookups.colors();
    $scope.shapes = lookups.shapes();
    $scope.results = search.results();

  $scope.isFilterColor = function(result){
    var found = false;
    angular.forEach($scope.colors, function(value,index){
        if(value.selected){
          console.log(value.id);
          if(result.colors.indexOf(value.id)!= -1)
            found = true;
        }
    });
    return found;
  };

  $scope.isFilterShape = function(result){
    var found = false;
    angular.forEach($scope.shapes, function(value,index){
        if(value.selected){
          if(result.shape == value.id)
            found = true;
        }
    });
    return found;
  };

    $scope.searchFn = function (result) {
      if ( $scope.isFilterShape(result) && $scope.isFilterColor(result) ) {
        return true;
      }
  };

}]);

我已经完成了查找&#39;字典变成数组所以在html页面上你需要做一些小改动才能正确显示颜色和形状名称。