Dujard
Dujard

Reputation: 309

filter select multiple angularJS

I'm a beginner with Angular and i have a multiple select in order to filter a list by name.

<select multiple ng-options="data.name for data in datas" ng-model="filterData">
</select>

I can filter with only one value by doing this :

<div class="container " data-ng-repeat="data in datas | filter : filterData[0].name">

but in my case i want to pass an array to the filter in order to filter with multiple values in same time

I must to create my own filter to do this ?

{
         "datas": [
            {"name": "first", "id": 1},
            {"name": "two", "id": 2},
            {"name": "three", "id": 3},
        ]
}

Thanks

Upvotes: 1

Views: 859

Answers (2)

micha
micha

Reputation: 1238

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

  myApp.controller('myController', myController);

  function myController($scope) {
    $scope.datas = [{
      "name": "first",
      "id": 1
    }, {
      "name": "two",
      "id": 2
    }, {
      "name": "three",
      "id": 3
    }, ];

    $scope.filterData = [];

    $scope.byArray = function(myArray) {
      return function(item) {
        return !myArray.some(function(word) {
          return item.name.indexOf(word.name) > -1;             
        });
      };

    }
  }
<div ng-app="myApp" ng-controller="myController">
  <select multiple ng-multible="true" size="3" ng-options="data.name for data in datas" ng-model="filterData">
  </select>
  <div class="container" data-ng-repeat="data in datas | filter : byArray(filterData)">{{data.name}}
  </div>
</div>
<script src="https://code.angularjs.org/1.3.11/angular.js"></script>

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

You can make a custom filter and pre-define some filter values:

<div class="container " data-ng-repeat="data in datas | filter : byArray">

var _filterTheseWords = ["first", "two", "three"];
$scope.byArray = function(item) {
    return _filterTheseWords.some(word) {
        return item.name.indexOf(word) > -1;
    });
}

Upvotes: 1

Related Questions