How to filter (key, value) with ng-repeat in AngularJs?
I am trying to do something like :
AngularJs Part:
function TestCtrl($scope)
{
$scope.items = {
‘A2F0C7’:{‘secId’:’12345′, ‘pos’:’a20′},
‘C8B3D1’:{‘pos’:’b10′}
};
$scope.hasSecurityId = function(k,v)
{
return v.hasOwnProperty(‘secId’);
}
}
But somehow, it is showing me all items. How can I filter on (key,value) ?
Solutions/Answers:
Solution 1:
Angular filters can only be applied to arrays and not objects, from angular’s API –
“Selects a subset of items from array and returns it as a new array.”
You have two options here:
1) move $scope.items
to an array or –
2) pre-filter the ng-repeat
items, like this:
<div ng-repeat="(k,v) in filterSecId(items)">
{{k}} {{v.pos}}
</div>
And on the Controller:
$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/
Solution 2:
My solution would be create custom filter and use it:
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;
};
});
And in html:
<div ng-repeat="(k,v) in items | with:'secId'">
{{k}} {{v.pos}}
</div>
Solution 3:
Also you can use ng-repeat
with ng-if
:
<div ng-repeat="(key, value) in order" ng-if="value > 0">
Solution 4:
Or simply use
ng-show="v.hasOwnProperty('secId')"
See updated solution here:
Solution 5:
You can simply use angular.filter module, and then you can filter even by nested properties.
see: jsbin
2 Examples:
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>
Solution 6:
It is kind of late, but I looked for e similar filter and ended using something like this:
<div ng-controller="TestCtrl">
<div ng-repeat="(k,v) in items | filter:{secId: '!!'}">
{{k}} {{v.pos}}
</div>
</div>