最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - angularJS filter expression in ng-repeat - Stack Overflow

programmeradmin2浏览0评论

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

  • 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.

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.
Share Improve this question edited Mar 24, 2014 at 22:01 Maxim Shoustin 77.9k29 gold badges210 silver badges228 bronze badges asked Mar 24, 2014 at 21:55 Annie CAnnie C 8042 gold badges14 silver badges32 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 8

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

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)

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

Use two ng-repeats, one after another:

1st : Filter on anything that has checkbox checked AND has a condition

2nd : Filter on things that don't have conditions

发布评论

评论列表(0)

  1. 暂无评论