在AngularJs中动态创建过滤器和匹配复选框

时间:2014-06-05 13:50:34

标签: angularjs angularjs-filter

我有很多数据点,有几种类型;

JSON文件:

{
  "items":[
    {
      "id:": 1,
      "type": "type1", //typeN isn't tied to id=N
      ... : ...
    },
    {
      "id:": 2,
      "type": "anotherType",
      ... : ...
    },
    {...},{...},{...},...
  ]
}

我想用DOM中的复选框过滤这些结果。所以首先我想让他们进入DOM。所以我需要在数据中找到唯一的类型。我通过Controller中的这个函数来做到这一点:

var itemTypeList = function(){
  if ($scope.hasOwnProperty('allItems')){ //this is to ensure async load completed
    var uniqTypes = [];
    for (var i=0 ; i < $scope.allItems.length ; i++){
      if (uniqTypes.indexOf($scope.allItems[i].type) < 0){
        uniqTypes.push($scope.allItems[i].type);
      }
    }
    $scope.uniqTypes = uniqTypes;
    return $scope.uniqTypes;
  }
};

然后我将它们放在HTML中:

<!-- These are what will be shown/hidden -->
<div class="">
  <div class="col-md-4" ng-repeat="item in allItems | filter:showItem">
    {{item.name}}
  </div>
</div>

<!-- this is the filter section -->
<div class="col-md-12" ng-repeat="uT in uniqTypes">
  <label>{{uT}}</label>
  <!-- here is where the accompanying checkbox should go -->
</div>

到目前为止,我的Controller Filter看起来像这样:

$scope.showItem = function(item){
   return item.type === $scope.Filter.item1 || 
     item.type === $scope.Filter.type2;
     //this is static, and I only typed 2 of the many....
};

并且输入复选框类似于

<input type="checkbox" ng-model="Filter.uT" ng-true-value="{{uT}}"/><br/>

问题是过滤器是静态的,我不得不手动输入类型。第二个问题是复选框ng模型不能像ng-model="Filter.{{uT}}"那样定义。我只能找到静态定义模型的例子。如何更改过滤器和输入ng-repeat以使用我已找到的uniqueTypes(uT)?

1 个答案:

答案 0 :(得分:2)

无法看到整个画面,但似乎你想要这样的东西:

<div class="col-md-12" ng-repeat="uT in uniqTypes">
  <label>{{uT}}</label>
  <input type="checkbox" ng-model="Filter[uT]"/>
</div>

复选框的值将为true或false - &gt; $ scope.Filter.type2将为true / false

$scope.Filter = {};

$scope.showItem = function(item){
   return $scope.Filter[item.type];
};

将返回true或false

基本版

fiddle

如果您想让它们最初显示,并单击取消隐藏,则需要首先通过键[val]对填充$scope.Filter。这可以在您动态创建uniqueTypes列表时完成。

以下是fiddle显示并初步检查