property example array javascript angularjs frameworks ng-repeat angular-filters

javascript - example - ng-repeat order by



Cómo filtrar(clave, valor) con ng-repeat en AngularJs? (8)

Estoy tratando de hacer algo como:

<div ng-controller="TestCtrl"> <div ng-repeat="(k,v) in items | filter:hasSecurityId"> {{k}} {{v.pos}} </div> </div>

Parte AngularJs:

function TestCtrl($scope) { $scope.items = { ''A2F0C7'':{''secId'':''12345'', ''pos'':''a20''}, ''C8B3D1'':{''pos'':''b10''} }; $scope.hasSecurityId = function(k,v) { return v.hasOwnProperty(''secId''); } }

Pero de alguna manera, me está mostrando todos los artículos. ¿Cómo puedo filtrar (clave, valor)?


Aunque esta pregunta es bastante antigua, me gustaría compartir mi solución para desarrolladores angulares 1. El punto es simplemente reutilizar el filtro angular original, pero pasar transparentemente cualquier objeto como una matriz.

app.filter(''objectFilter'', function ($filter) { return function (items, searchToken) { // use the original input var subject = items; if (typeof(items) == ''object'' && !Array.isArray(items)) { // or use a wrapper array, if we have an object subject = []; for (var i in items) { subject.push(items[i]); } } // finally, apply the original angular filter return $filter(''filter'')(subject, searchToken); } });

Úselo así:

<div> <input ng-model="search" /> </div> <div ng-repeat="item in test | objectFilter : search"> {{item | json}} </div>

aquí hay un plunker


Es un poco tarde, pero busqué un filtro similar y terminé usando algo como esto:

<div ng-controller="TestCtrl"> <div ng-repeat="(k,v) in items | filter:{secId: ''!!''}"> {{k}} {{v.pos}} </div> </div>


Hice un poco más de un filtro genérico que ya he usado en múltiples proyectos:

  • object = el objeto que debe filtrarse
  • campo = el campo dentro de ese objeto que filtraremos
  • filter = el valor del filtro que debe coincidir con el campo

HTML:

<input ng-model="customerNameFilter" /> <div ng-repeat="(key, value) in filter(customers, ''customerName'', customerNameFilter" > <p>Number: {{value.customerNo}}</p> <p>Name: {{value.customerName}}</p> </div>

JS:

$scope.filter = function(object, field, filter) { if (!object) return {}; if (!filter) return object; var filteredObject = {}; Object.keys(object).forEach(function(key) { if (object[key][field] === filter) { filteredObject[key] = object[key]; } }); return filteredObject; };


Los filters angulares solo se pueden aplicar a matrices y no a objetos, desde la API de angular:

"Selecciona un subconjunto de elementos de la matriz y lo devuelve como una nueva matriz".

Tienes dos opciones aquí:
1) mueve $scope.items a una matriz o -
2) prefiltrar los elementos ng-repeat , como este:

<div ng-repeat="(k,v) in filterSecId(items)"> {{k}} {{v.pos}} </div>

Y en el controlador:

$scope.filterSecId = function(items) { var result = {}; angular.forEach(items, function(value, key) { if (!value.hasOwnProperty(''secId'')) { result[key] = value; } }); return result; }

jsfiddle : http://jsfiddle.net/bmleite/WA2BE/


Mi solución sería crear un filtro personalizado y usarlo:

app.filter(''with'', function() { return function(items, field) { var result = {}; angular.forEach(items, function(value, key) { if (!value.hasOwnProperty(field)) { result[key] = value; } }); return result; }; });

Y en html:

<div ng-repeat="(k,v) in items | with:''secId''"> {{k}} {{v.pos}} </div>



Simplemente puede usar el módulo angular.filter y luego puede filtrar incluso por propiedades anidadas.
ver: jsbin
2 ejemplos:

JS:

angular.module(''app'', [''angular.filter'']) .controller(''MainCtrl'', function($scope) { //your example data $scope.items = { ''A2F0C7'':{ secId:''12345'', pos:''a20'' }, ''C8B3D1'':{ pos:''b10'' } }; //more advantage example $scope.nestedItems = { ''A2F0C7'':{ details: { secId:''12345'', pos:''a20'' } }, ''C8B3D1'':{ details: { pos:''a20'' } }, ''F5B3R1'': { secId:''12345'', pos:''a20'' } }; });

HTML:

<b>Example1:</b> <p ng-repeat="item in items | toArray: true | pick: ''secId''"> {{ item.$key }}, {{ item }} </p> <b>Example2:</b> <p ng-repeat="item in nestedItems | toArray: true | pick: ''secId || details.secId'' "> {{ item.$key }}, {{ item }} </p>


También puede usar ng-repeat con ng-if :

<div ng-repeat="(key, value) in order" ng-if="value > 0">