Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS ng-repeat filtering with an OR-statement

So I have a dataset of companies stored in a variable in a controller.

$scope.companies = [
    {
        name: "first company",
        type: ["a", "b"]
    },
    {
        name: "second company",
        type: ["b"]
    },
    {   
        name: "third company",
        type: ["c"]
    }
]

Then i have my list where I want to list all companies of either a or b. I thought sending and array would work as an or-statement. Turns out it's more like an and-statement.

<ul>
    <li ng-repeat="company in companies | filter:filters{type: ['a', 'b']}">
        {{company.name}}
    </li>
</ul>

The code above would list "first company" while I would like it to list both the "first company" and the "second company". I know I could manipulate the $scope.companies dataset from within the controller, but I'd like to know if there's any "native" way to achieve this first.

Best regards! // Richard

like image 707
Richard Lilja Avatar asked Aug 17 '13 09:08

Richard Lilja


People also ask

How do I filter data in ng-repeat?

The ng-repeat values can be filtered according to the ng-model in AngularJS by using the value of the input field as an expression in a filter. We can set the ng-model directive on an input field to filter ng-repeat values.

How do you condition in NG-repeat?

You can add condition using ng-if also and this is effective too. You can apply any condition to your list using ng-if attribute. In below example, I have put condition where Age > 20 and IsActive is true. ng-repeat will fetch all records which full fill this scenario.

What is correct way to apply multiple filters in Angular?

Using filters in view templates Filters can be applied to the result of another filter. This is called "chaining" and uses the following syntax: {{ expression | filter1 | filter2 | ... }} E.g. the markup {{ 1234 | number:2 }} formats the number 1234 with 2 decimal points using the number filter.

What are the correct way to apply filter in AngularJS?

In AngularJS, you can also inject the $filter service within the controller and can use it with the following syntax for filter. Syntax: $filter("filter")(array, expression, compare, propertyKey) function myCtrl($scope, $filter) { $scope. finalResult = $filter("filter")( $scope.


1 Answers

Your only options is to use a filter using a function:

<ul>
    <li ng-repeat="company in companies | filter:customFunction">
        {{company.name}}
    </li>
</ul>

Where

$scope.customFunction = function(item){ /* true if you want item, false if not */ }

Source: http://docs.angularjs.org/api/ng.filter:filter#parameters

like image 130
basarat Avatar answered Sep 29 '22 08:09

basarat