角度1:根据对象属性过滤ng-repeat输出

时间:2016-03-31 05:12:25

标签: angularjs

我的视图中有简单的ng-repeat,可以打印来自对象的数据。

  <div
    ng-repeat="item in toDoItems |
               orderBy: 'createdAt'
               track by item.createdAt"
  >
    <b>Content:</b> {{item.content}}
  </div>

我正在打印的对象如下所示:

     {
        "content" : "some content",
        "createdAt" : "1459401001460",
        "completed" : false
      },
      {
        "content" : "some content",
        "createdAt" : "1459401001325",
        "completed" : true
       }

我只想打印false符合"completed"值的{{1}}项。

我试过了,但它会给我错误:ng-repeat only objects with specific property value - custom filter?

4 个答案:

答案 0 :(得分:1)

使用此自定义过滤器

app.filter('myFilter', function () {
    return function (items) {
        if (!items) {
            return true;
        }
        if (items.length == 0) {
            return items;
        }
        var newItems = [];
        angular.forEach(items, function(item, index){
           if(item.completed==true || item.completed=='true'){
               newItems.push(item)
           }
        })
        return newItems ;
    };
});

您的HTML是:

 <div ng-repeat="item in toDoItems | myFilter track by $index">
        <b>Content:</b> {{item.content}}
  </div>

答案 1 :(得分:1)

您可以使用此格式的过滤器。

.attr('onclick','test()');
var myapp = angular.module('app', []);
myapp.controller('Main', function ($scope) {
  $scope.data =[
       {
         "content" : "some content",
         "createdAt" : "1459401001460",
         "completed" : false
       },
      {
         "content" : "some content",
         "createdAt" : "1459401001325",
         "completed" : true
       },
       {
         "content" : "some content2",
         "createdAt" : "1459401001460",
         "completed" : false
       },
      {
         "content" : "some content",
         "createdAt" : "1459401001325",
         "completed" : true
       },
       {
         "content" : "some content3",
         "createdAt" : "1459401001460",
         "completed" : false
       },
      {
         "content" : "some content",
         "createdAt" : "1459401001325",
         "completed" : true
       }
 ];
});

答案 2 :(得分:0)

<b ng-show='item.completed==false'>Content:</b> 
<span ng-show='item.completed==false'>{{item.content}}</span>

答案 3 :(得分:0)

使用angular filter plugin,更改您的代码,如下所示

注入

<div
        ng-repeat="item in toDoItems | filterBy: ['completed']: true |
                   orderBy: 'createdAt'
                   track by item.createdAt"
      >
        <b>Content:</b> {{item.content}}
      </div>