1

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.

4
  • 1
    why do you use ng-init??? don't you wanna use ng-repeat??? Commented Nov 5, 2015 at 8:58
  • I need to assign variable only with one of the objects within that array, I don't need to output anything in the view. I can create filter with forEach loop, but I wonder if there's a built-in way to select the subset of items from array in angular. Commented Nov 5, 2015 at 8:59
  • ok try <div ng-repeat="foo in foobar | filter:{id:25}"> Commented Nov 5, 2015 at 9:01
  • it shows just the filtered object ! Commented Nov 5, 2015 at 9:01

3 Answers 3

3

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>

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.