Search code examples
javascripthtmlangularjsjsonangular-filters

Filter Embedded Json element from a Collection using AngularJS HTML


I'm having a JSON Collection, I wish to dispay Email ID which is marked as IsPreffered = TRUE using AngularJS HTML without . user.Name

My JSON Collection :

{ "user" : [
    {
        "Name" : "B. Balamanigandan",
        "Email": [
            {
                "Id": "bala@gmail.com",
                "IsPreffered": true
            },
            {
                "Id": "mani@gmail.com",
                "IsPreffered": false
            }
    ]}
]};

HTML Source Code:

<div>
    <h3>Employee Details:</h3>
    <span> {{collection.user.Name}} </span>
    <span> {{collection.user.Email.Id}} </span>
</div>

The Collection user contains only one document. So, I didn't use ng-repeat. user is a Collection not a Document. One more check I need. If more than one email has `IsPreferred == true', then I have the take the last one. Kindly assist me.

Kindly filter the condition using HTML Level not in JavaScript Level. Kindly assist me.


Solution

  • instead of this:

    <div>
        <h3>Employee Details:</h3>
        <span> {{collection.user.Name}} </span>
        <span> {{collection.user.Email.Id}} </span>
    </div>
    

    you will have to do this:

    <div>
        <h3>Employee Details:</h3>
        <span> {{collection.user[0].Name}} </span>
    
        <span ng-repeat="email in collection.user[0].email| filter: {IsPreffered : 'true'}"> {{email.Id}} </span>
    </div>
    

    You have to use array syntax, because although there is only 1 user object, it is structured in the json as an array ( note the [ ] , same for Email).

    Here is a fiddle: http://jsfiddle.net/Lvc0u55v/5593/

    UPDATE: For showing only the last email which is true, use ng-if:

    <span ng-repeat="email in collection.user[0].Email| filter: {IsPreffered : true} " ng-if="$last"> {{email.Id}}</span>
    

    Here is the updated fiddle: http://jsfiddle.net/Lvc0u55v/5594/