Guy
Guy

Reputation: 139

Dynamic multi-column filtering with angularJS ng-repeat and ng-model

I have figured out static (hard-coded) multi-column filtering; Here.

<p><input type="text" ng-model="s1"></p>
<p><input type="text" ng-model="s2"></p>

<ul>
<li ng-repeat="x in names | filter:{name:s1} | filter:{country:s2} | orderBy:'country'">
{{ (x.name | uppercase) + ', ' + x.country }}
</li>
</ul>

However, I want to be able to create the text box filters dynamically based on the model (ie. for any # of columns). It seems like it should be something like this, but the text boxes do nothing.

<div ng-repeat="n in names">
    <input type="text" ng-model="n.column" >
</div>

<ul>
  <li ng-repeat="x in names | filter:{name:name} | filter:{country:country} | orderBy:'country'">
    {{ (x.name | uppercase) + ', ' + x.country }}
  </li>
</ul>

I've searched all around, and I find it hard to believe something like this hasn't been done [often enough to be found by my searching].

Any help is appreciated.

Upvotes: 4

Views: 10338

Answers (1)

Darshan P
Darshan P

Reputation: 2241

DEMO

<div ng-repeat="n in headers">
    <input type="text" ng-model="filters[n.column]" >
</div>

<ul>
  <li ng-repeat="x in names | filter:{name:filters.name} | filter:{country:filters.country} | orderBy:'country'">
    {{ (x.name | uppercase) + ', ' + x.country }}
  </li>
</ul>

Controller

function namesController($scope) {
    $scope.names = [
        {name:'Jani',country:'Norway'},
        {name:'Hege',country:'Sweden'},
        {name:'Kai',country:'Denmark'}
    ];

    $scope.filters = {};

    $scope.headers = [
      {column: "name"},
      {column: "country"}
    ];
}

Upvotes: 5

Related Questions