chris Frisina
chris Frisina

Reputation: 19688

Dynamically create filter and matching checkboxes in AngularJs

I have many data points, with several types;

JSON file:

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

I want to filter these results with checkboxes in the DOM. So first I want to get them into the DOM. So I need to find the unique types in the data. I do this through this function in the 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;
  }
};

and then I place them in the HTML like so:

<!-- 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>

So far, my Controller Filter looks like this:

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

and the input check box looks like

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

The problem is that the filter is static, and I had to manually put in the types. The second problem is that the checkbox ng-model can't be defined like so ng-model="Filter.{{uT}}". I can only find examples of statically defined models. How do I change the filter and the input ng-repeat to use the uniqueTypes (uT) that I have already found?

Upvotes: 0

Views: 1975

Answers (1)

gorpacrate
gorpacrate

Reputation: 5561

Can't see the whole picture, but it seems like you want something like this:

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

value of checkbox will be true or false --> $scope.Filter.type2 will be true/false

$scope.Filter = {};

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

will return true or false

fiddle of the basic version

If you want to have them showing initially, and click to unhide, the $scope.Filter needs to be populated first by a key[val] pair. This can be done when you dynamically create the uniqueTypes list.

Here is this fiddle of it showing and checked initially

Upvotes: 2

Related Questions