ng if with angular for string contains
ES2015 UPDATE
ES2015 have String#includes
method that checks whether a string contains another. This can be used if the target environment supports it. The method returns true
if the needle is found in haystack else returns false
.
ng-if="haystack.includes(needle)"
Here, needle
is the string that is to be searched in haystack
.
See Browser Compatibility table from MDN. Note that this is not supported by IE and Opera. In this case polyfill can be used.
You can use String#indexOf
to get the index of the needle in haystack.
- If the needle is not present in the haystack -1 is returned.
- If needle is present at the beginning of the haystack 0 is returned.
- Else the index at which needle is, is returned.
The index can be compared with -1
to check whether needle is found in haystack.
ng-if="haystack.indexOf(needle) > -1"
For Angular(2+)
*ngIf="haystack.includes(needle)"
ng-if="select.name.indexOf('?') !== -1"
All javascript methods are applicable with angularjs because angularjs itself is a javascript framework so you can use indexOf() inside angular directives
<li ng-repeat="select in Items">
<foo ng-repeat="newin select.values">
<span ng-if="newin.label.indexOf(x) !== -1">{{newin.label}}</span></foo>
</li>
//where x is your character to be found
Only the shortcut syntax worked for me *ngIf.
(I think it's the later versions that use this syntax if I'm not mistaken)
<div *ngIf="haystack.indexOf('needle') > -1">
</div>
or
<div *ngIf="haystack.includes('needle')">
</div>