AngularJS - Using indexOf inside ng-repeat to show/hide values

Oam Psy picture Oam Psy · Oct 15, 2014 · Viewed 33.7k times · Source

I have a JSON file that contains a bunch of data:

myData.JSON:

{
"Addresses": {
    "AddressList": [
        {
            "HouseNumber": 201,
            "Street": "Victoria Lane",
            "Postcode": "SW1 8ES"
        },
        {
            "HouseNumber": 10,
            "Street": "Allen Close",
            "Postcode": "NG2 3TD"
        },
        {
            "HouseNumber": 57,
            "Street": "Thomas Street",
            "Postcode": "DR12 6TE"
        },
        {
            "HouseNumber": 57,
            "Street": "Old Lister Street",
            "Postcode": "OL4 5TH"
        },
        {
            "HouseNumber": 45,
            "Street": "Milk Round Street",
            "Postcode": "MK6 4HG"
        },
        {
            "HouseNumber": 102,
            "Street": "Jersey Quarter Avenue",
            "Postcode": "DR12 6TE"
        },
        {
            "HouseNumber": 845,
            "Street": "MR HAPPY STREET",
            "Postcode": "MR3 0FJ"
        }
    ]
}

Im trying to show a div if a match on the returned value from Street is found via a indexOf

HTML:

<div ng-repeat="address in Addresses.AddressList">
    {{ address.HouseNumber }}, {{ address.Street}}, {{ address.Postcode }}
    <div ng-show="address.Street.toLowerCase().indexOf('MR HAPPY STREET') == 0">
        MR HAPPY STREET WAS FOUND
    </div>
    <div ng-show="address.Street.toLowerCase().indexOf('Milk Round Street') == 0">
        Milk Round Street WAS FOUND
    </div>
</div>

This doesnt seem to work. Can you perform such indexOf via an ng-show?

Answer

ababashka picture ababashka · Oct 15, 2014

Your problem is that you compare 2 strings which are not the same: after use toLowerCase() function your string Milk Round Street looks like milk round street. So indexOf() will return -1. That's why you need to compare 2 strings in lower case, such as:

<div ng-show="address.Street.toLowerCase().indexOf('mr happy street') == 0">

or:

<div ng-show="address.Street.toLowerCase().indexOf(('MR HAPPY STREET').toLowerCase()) == 0">