Search code examples
angularjsangular-filters

AngularJS filter array and display property of first object in Angular view


I am trying something like this.

<select  data-ng-model="modelName" 
    data-ng-options="item.id as (item.id + ' - ' +item.name) for item in options">
    <option value=''>Select</option>
</select>
{{options | filter:modelName}}

options are an array of object. The object structure is {id:XYZ, name:ABC}. So array is

[{id:XYZ, name:ABC},{id:XYZ1, name:ABC1},{id:XYZ2, name:ABC2}]

For above code my output is being

{id:XYZ, name:ABC}

But I want only 'ABC'

Note: I know that I can use custom filter for it. But is there any better approach? Certainly for this small thing I do not want to create any directive also.


Solution

  • You can just wrap the entire angular expression with a bracket and access the first item's name property.

    DEMO

    {{ (options | filter:modelName)[0].name }}