Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularJS filter expression in ng-repeat

I would like to know what is the most elegant and simple way to implement this. I need to add a filter expression for a ng-repeat that would filter 2 conditions from one property.

In this example http://plnkr.co/edit/OMQxXvSjtuudMRGE4eZ8?p=preview

  • If you enter A, it would display checkbox for A,
  • enter B - display checkbox for B.

But I want to display the specified checkboxes plus anything with empty condition. There is no condition for C, so:

  • if you enter A, I want to display both A and C checkboxes,
  • enter B, I want to display both B and C checkboxes.
like image 342
Annie C Avatar asked Mar 24 '14 21:03

Annie C


People also ask

How do I filter 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.

What is Ng-repeat in AngularJS?

AngularJS ng-repeat Directive The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.

How do I get an index value in ng-repeat?

Note: The $index variable is used to get the Index of the Row created by ng-repeat directive. Each row of the HTML Table consists of a Button which has been assigned ng-click directive. The $index variable is passed as parameter to the GetRowIndex function.


3 Answers

I would create custom filter like:

app.filter('myfilter', function() {
   return function( items, condition) {
    var filtered = [];

    if(condition === undefined || condition === ''){
      return items;
    }

    angular.forEach(items, function(item) {          
       if(condition === item.condition ||  item.condition === ''){
         filtered.push(item);
       }
    });

    return filtered;
  };
});

and usage:

<span ng-repeat="charge in charges  |  myfilter:level.condition">

See Demo in Plunker

It looks pretty elegant and clear.

Hope it will help

like image 174
Maxim Shoustin Avatar answered Sep 30 '22 11:09

Maxim Shoustin


I think you can do this pretty easily with just a filter expression function on your scope like this;

$scope.filterExpression = function(charge) {
  return (!$scope.level || !charge.condition || 
          ($scope.level.condition.toUpperCase() === charge.condition.toUpperCase()));
}

and call it like this;

<span ng-repeat="charge in charges | filter:filterExpression">

plunkr (corrected)

like image 21
cirrus Avatar answered Sep 30 '22 11:09

cirrus


you can use : data-ng-repeat="charge in charges | filter:searchText" data-ng-if="filter = searchText.Name"

like image 45
SoloThink Avatar answered Sep 26 '22 11:09

SoloThink