Angular.js:filtro ng-repeat por la ausencia de clave/valor
-
21-12-2019 - |
Pregunta
Quiero filtro ng-repeat, de modo que se muestra sólo las filas donde todos los pares clave/valor están presentes.
HTML
<div ng-app="myApp" ng-controller="oneController">
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>Country</th>
<th>1960</th>
<th>1970</th>
</tr>
<tbody>
<tr ng-repeat="country in countries | orderBy: country.name">
<td>{{country.name}}</td>
<td>{{country.1960 | number}}</td>
<td>{{country.1970 | number}}</td>
</tr>
</tbody>
</table>
Javascript
angular.module('myApp', []).
controller('oneController', function($scope) {
$scope.countries = [
{"name":"Aruba", "1960":"1567"},
{"name":"Andorra","1960":77865,"1970":78360},
];
});
Así, en este ejemplo, no quiero Aruba muestra, sólo Andorra.
Ejemplo completo @ CSSDeck: http://cssdeck.com/labs/1aksiuuu (Yo no quiero Aruba muestra)
Solución
La expansión en el filtro personalizado concepto, creo que el punto es que usted no sepa que la propiedad puede faltar para un objeto dado.Mediante un bucle de todas las propiedades de todos los objetos, puede crear una lista maestra de todos los bienes que existe en al menos un objeto:
$scope.properties = function(){
var props = [];
angular.forEach($scope.countries, function(country){
for(var prop in country){
if(props.indexOf(prop) == -1)
props.push(prop);
}
});
return props;
};
Ahora usted puede hacer una función de filtro que cheques en contra de esta lista:
$scope.hasAllProperties = function(item){
var found = true;
angular.forEach($scope.properties(), function(prop){
if(item[prop] == undefined){
found = false;
return;
}
});
return found;
}
HTML:
<tr ng-repeat="country in countries | filter: hasAllProperties | orderBy: country.name">
Usted podría desea almacenar en caché la lista maestra de propiedades para reducir el número de veces que $scope.properties()
se llama.
Demo (También he quitado una propiedad de la Argentina en esta demo)
Otros consejos
siempre puede hacer un filtro personalizado:
<tr ng-repeat="country in countries | filter:allProperties | orderBy: country.name">
y el filtro
$scope.allProperties = function(item) {
return item.name && item.1960 && item.1970
}
One solution is to use the filter
filter:
<tr ng-repeat="country in countries | filter:{name: '', 1960: '', 1970: ''} | orderBy:'name'">
Create a filter inside your controller like below:
$scope.search = function (item){
return item.hasOwnProperty("1970");
};
use the filter like below:
<tr ng-repeat="country in countries | filter:search | orderBy: country.name">
Forked a new URL from yours: http://cssdeck.com/labs/kggmrzow
Try this:
<tr ng-repeat="country in countries | orderBy: country.name">
<label ng-show="country.1960!=undefined && country.1970!=undefined">
<td>{{country.name}}</td>
<td>{{country.1960 | number}}</td>
<td>{{country.1970 | number}}</td>
</label>
</tr>