Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display one item from array in AngularJS without using ng-repeat

Tags:

angularjs

I have JSON array like:

var data = [
{
  "name": "Jim",
  "age" : 25
},
{
  "name": "Jerry",
  "age": 27
}
];

in HTML:

<ul>
  <li ng-repeat="val in data | filter:{age: age}:true">{{val.name}}</li>
</ul>

The above code is working fine as i want the output, but i don't want to use ng-repeat where it creates loop and then i filter.

is there any another way where i can directly select the DATA from array where age = age ??

like image 784
Jay Avatar asked Dec 20 '22 14:12

Jay


2 Answers

Filters can be used in any angular expression (there is nothing ngRepeat-specific about them).
(They can be even used in JavaScript.)

E.g. the following expression displays the data associated with the first user (limitTo:1) that has an age of 25 (filter:{age: 25}), formatted as JSON (json):

{{data | filter:{age: 25}:true | limitTo:1 | json}}

See, also, this short demo.

like image 112
gkalpak Avatar answered Jan 19 '23 00:01

gkalpak


As mentioned by @link in comments, there is no way to pluck the object with the required age from the array without looping through it. However, you're right in thinking that using ng-repeat here is not appropriate if you only want to display a single object from the array, so ideally the required object should be stored in your controller.

One approach would be to use $filter in your controller instead:

$scope.obj_with_correct_age = $filter("filter")(data, {age: age});

<li>{{ obj_with_correct_age.name }}</li>
like image 40
Elise Avatar answered Jan 18 '23 23:01

Elise