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
??
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With