Oam Psy Oam Psy - 6 months ago 32
AngularJS Question

ng-show/hide - based on a substring in a string

I'm familiar with using ng-show and ng-hide when my bound data contains a specific word or piece of text. For example:

<div ng-show="myArray.Length > 20">
Show something
</div>

<div ng-show="myData.Name == 'Harry Roberts'">
Show something
</div>


However, how can i use
ng-show
to show when the bound data contains a certain value, for example, 'Current'. For example, if my JSON data:

{
"MyAddresses": [
{
"Entry" : "1",
"Period" : "2011 - current",

}, {
"Entry" : "2",
"Period" : "2003 - 2011",

}, {
"Entry" : "3",
"Period" : "1998 - 2001",

}
]
}


<div ng-show="myData.MyAddresses.Period ~ 'Current'">
Show something
</div>

Answer

Use the function indexOf to search for a substring in a string. It will return the position of the search string if found or will return -1.

So you can use an expression like myData.MyAddresses.Period.indexOf('Current') != -1 to show/hide data

Comments