Domanda

I'm following this great post: How to filter a list in AngularJS using several links

Now I'd like to display data filtered by multiple parameters on click.

html

<div ng-app>
  <span ng-click="myFilter = {type: 1}">Type 1</span> | 
  <span ng-click="myFilter = {type: 2}">Type 2</span> |
  <span ng-click="myFilter = {type: 3}">Type 3</span> |
  <!-- multiple filter - not working -->
  <span ng-click="myFilter = [{type: 1}, {type:3}]">Types 1 & 3</span> |
  <span ng-click="myFilter = null">No filter</span>
  <ul ng-controller="Test">
    <li ng-repeat="person in persons | filter:myFilter">{{person.name}}</li>
  </ul>
</div>

js

function Test($scope) {
  $scope.persons = [{type: 1, name: 'Caio'}, {type:2, name: 'Ary'}, {type:1, name: 'Camila'}, , {type:3, name: 'Daniel'}];
}

The multiple parameters filter example doesn't work that way. Is there a simple and generic way to achieve that, without coding a custom filter ?

I updated the jsfiddle: http://jsfiddle.net/pkxPa/89/

Any idea ? Maybe there is a better way like using ng-show (like in this post: Show hidden div on ng-click within ng-repeat) ?

Thanks

È stato utile?

Soluzione

I've updated the plunkr (http://jsfiddle.net/pkxPa/91/) to fix a few minor errors and demonstrate how you can do it with a custom function. Unfortunately, I dont think there is a way to do it inline as you tried.

Moved the controller decleration to top most div

<div ng-app ng-controller="Test">
  <span ng-click="myFilter = {type: 1}">Type 1</span> | 
  <span ng-click="myFilter = {type: 2}">Type 2</span> |
  <span ng-click="myFilter = {type: 3}">Type 3</span> |
  <!-- multiple filter - not working -->
  <span ng-click="myFilter = myFunction">Types 1 & 3</span> |
  <span ng-click="myFilter = null">No filter</span>
  <ul >
    <li ng-repeat="person in persons | filter:myFilter">{{person.name}}</li>
  </ul>
</div>

Removed duplicate comma from your persons array that was resulting in an undefined object and added a custom filter

    function Test($scope) {
          $scope.persons = [{type: 1, name: 'Caio'}, {type:2, name: 'Ary'}, 
{type:1, name: 'Camila'}, {type:3, name: 'Daniel'}];
            $scope.myFunction = function(val) {

            return (val.type != 2);
            };
        }

See the AngularJS documentation here for more info http://docs.angularjs.org/api/ng/filter/filter

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top