Reputation: 1305
I have an array of objects and I need to return object containing specific property.
$scope.foobar = [
{"id": 15, "name": "bar1"},
{"id": 25, "name": "bar2"},
{"id": 215, "name": "bar3"},
{"id": 7415, "name": "bar4"}
];
I need to assign a new variable with the object where id
is 25
. The following does not work:
<div ng-init="item = foobar | filter: { id: 25 }">...</div>
How can I use angular filter without ng-repeat
to select the subset of items from array and return it as a new array.
Upvotes: 1
Views: 4747
Reputation: 2033
I know this question is too old to answer, but may be it will help other.
<span ng-bind="(foobar | filter : {id : 25 } : true)[0].name"></span>
you can also use $scope
variable instead of 25
Upvotes: 2
Reputation: 6958
If your view doesn't need it, don't put it in the template. If you don't want to write your own filtering function and use angular filterFilter (some of the naming fun with angular :)), inject it into your controller and set your variable there.
angular.module('myApp', [])
.controller('MainController', function ($scope, filterFilter) {
$scope.foobar = [
{"id": 15, "name": "bar1"},
{"id": 25, "name": "bar2"},
{"id": 215, "name": "bar3"},
{"id": 7415, "name": "bar4"}
];
// use the filter Filter to set your var
$scope.item = filterFilter($scope.foobar, {id: 25});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MainController">
{{item}}
</div>
Upvotes: 3
Reputation: 2115
You need a function that extracts the correct data:
$scope.getFoo = function(id){
for(var i = 0; i< foobar.length;++i)
if(foobar[i].id === id)
return foobar[i];
};
$scope.foobar = [
{"id": 15, "name": "bar1"},
{"id": 25, "name": "bar2"},
{"id": 215, "name": "bar3"},
{"id": 7415, "name": "bar4"}
];
HTML:
<div ng-init="item = getFoo(25)">...</div>
Upvotes: 1