数组过滤器 return 全部为空时
Array Filter return all when empty
我正在使用数组过滤 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 = [];
}
只需检查您 arrayFilter
的长度。如果长度 = 0 return 你的 list
;
if(arrayFilter && arrayFilter.length > 0){
return $filter("filter")(list, function(listItem){
return arrayFilter.indexOf(listItem[element]) != -1;
});
}
return list;
完整示例:JSBin
return 数组应该是这样的:
.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*/;
});
}
};
});
我正在使用数组过滤 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 = [];
}
只需检查您 arrayFilter
的长度。如果长度 = 0 return 你的 list
;
if(arrayFilter && arrayFilter.length > 0){
return $filter("filter")(list, function(listItem){
return arrayFilter.indexOf(listItem[element]) != -1;
});
}
return list;
完整示例:JSBin
return 数组应该是这样的:
.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*/;
});
}
};
});