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.
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>