Reputation: 6227
My code is outputting:
Using the model of $scope.selected = '123'
how can I edit it to only output:
Here's my view:
<body ng-controller="MainCtrl">
<ul>
<li ng-repeat="item in items">
{{item.color}}
</li>
</ul>
</body>
Here's my controller:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.selected = '123';
$scope.items = {
'123': {
color: 'red',
quantity: 3
},
'456': {
color: 'blue',
quantity: 7
}
};
});
I tried using a filter with selected
but didn't have any luck.
Upvotes: 1
Views: 1559
Reputation: 171698
By changing items to array:
$scope.items =[
{
id:'123',
color: 'red',
quantity: 3
},
{
id:'456',
color: 'blue',
quantity: 7
}
];
You can use built in filter
which is only available for arrays ( there was talk of object filtering also, not sure if it exists yet)
<li ng-repeat="item in items | filter: {id:selected}">
{{item.color}}
</li>
In general it is better to work with array data that allows sorting, filtering, indexing etc much easier than with objects
Upvotes: 2
Reputation: 1165
You can create a filter for this
.filter('myFilter', function() {
return function(obj, selected) {
if (!selected) return obj;
return {
value: obj[selected]
}
}
}
here is an example
Upvotes: 1
Reputation: 28750
Filters will only work on arrays, and as charlietfl mentioned you should probably switch it to that. If you can't you can use this, though I highly recommend against it:
<body ng-controller="MainCtrl">
<ul>
<li ng-repeat="(key, item) in items" data-ng-if="key == selected">
{{item.color}}
</li>
</ul>
</body>
Upvotes: 0