数组过滤器在空时返回全部

时间:2017-02-14 13:14:39

标签: javascript angularjs arrays filter ng-repeat

我用数组过滤ng-repeat。我希望ng-repeat在filterarray为空时显示所有内容。

HTML

<!DOCTYPE html>
<html ng-app='Test'>
<head>
  <script src="http://code.angularjs.org/1.1.1/angular.min.js"></script>
  <meta charset=utf-8 />
  <title>JS Bin</title>
</head>
<body ng-controller='Ctrl'>
  <div ng-repeat='letter in letters | inArray:filterBy:"id"'>{{letter.id}}</div>

</body>
</html>

JS

angular.module('Test', [])
.filter('inArray', function($filter){
    return function(list, arrayFilter, element){
        if(arrayFilter){
            return $filter("filter")(list, function(listItem){
                return arrayFilter.indexOf(listItem[element]) != -1;
            });
        }

    };
});

function Ctrl($scope) {
  $scope.letters = [
    {id: 'a', name:'nameA'},
    {id: 'b', name:'nameB'},
    {id: 'c', name:'nameC'},
    {id: 'd', name:'nameD'},
    {id: 'e', name:'nameE'}
  ];

  $scope.filterBy = [];
}

JSBIN: http://jsbin.com/buteyorabi/edit?html,js,output

2 个答案:

答案 0 :(得分:3)

只需检查arrayFilter的长度即可。如果length = 0,则返回list;

    if(arrayFilter && arrayFilter.length > 0){
        return $filter("filter")(list, function(listItem){
            return arrayFilter.indexOf(listItem[element]) != -1;
        });
    }

    return list;

完整示例:JSBin

答案 1 :(得分:0)

返回数组应该是这样的:

.filter('inArray', function($filter){
    return function(list, arrayFilter, element){
        if(arrayFilter){
            return $filter("filter")(list, function(listItem){
                var result = arrayFilter.indexOf(listItem[element]);
                return (result != -1)?listItem:/*something to like to return*/;
            });
        }

    };
});