Patrickkx Patrickkx - 1 month ago 15
AngularJS Question

AngularJS: Filter array by type

I want to filter the displayed elements of

$scope.drinks
array. The products is an array of objects, containing few elements with their own type:
food
or
drink
. I just want to filter the array if user clicks on the select option
food
or
drink
.

I was close to do it by myself, but experienced a lot of errors. I'm looking for most efficient way to do it.

Thanks for any help!

This is jsfiddle with whole app: https://jsfiddle.net/scgsc7or/25/

Edit: I've already tried a solution with
ng-model="filterCategory"
and
filter : filterCategory
, but something really weird is happening. Even if the array is filtered, if I click on some element it add very other position! Just look at the gif:
enter image description here

New jsfiddle: https://jsfiddle.net/scgsc7or/27/

Answer

You need to add an ng-model="filterCategory" on the select and then use it with filter : filterCategory in the ng-repeat

 <div class="col-xs-6">
  <select class="chooseCategory" ng-model="filterCategory">
    <option value="" disabled selected>- choose category -</option>
    <option value="drink">drink</option>
    <option value="food">food</option>
    <option value="">all positions</option>
  </select>
  <div class="itemListDiv">
    <ul class="list-group itemList">
      <li class="list-group-item" ng-hide="product.isHidden" ng-repeat="(id, product) in drinks | filter : filterCategory" ng-click="addToShoppingList(product)">
        <strong>{{ product.name }}</strong> - {{ product.price | currency }}
      </li>
    </ul>
  </div>
</div>

ok i changed the value passed to function addToShoppingList and then in js:

$scope.addToShoppingList = function(product) {
    var index = $scope.drinks.indexOf(product);
    var itemToAdd = $scope.drinks[index];
    itemToAdd.quantity = 1;
    $scope.itemsToBuy.push(itemToAdd);
    $scope.drinks.splice(index, 1);
   };