Search code examples
javascripthtmlangularjsangularjs-ng-repeatangularjs-filter

AngularJS: if item in loop equals current location then print specific class


I have below code:

<ul ng-init="urls = ['/home', '/news', '/contactUs']">
<li ng-repeat="url in urls>
<a class="current-page" href="{{url}}">
{{url}}
</a>
</li>
</ul>

For each <a> tag in the ng-repeat loop, if {{url}} is qual to window.location.href.split('?')[0] then I wants to print the current-page class for that <a> tag. Else, it should not be shown. In simple words I wants something like this: {{url || if(url == window.location.href.split('?')[0])}}

Is it possible with AngularJS ? Then how?


Solution

  • If you have ['example.com/home', 'example.com/news', 'example.com/contactUs'] then I suggest this:

    <a ng-class="{ 'current-page': (window.location.host + window.location.pathname).indexOf(url) >= 0 }">{{url}}</a>
    

    But if you have ['/home', '/news', '/contactUs'] then this is enough:

    <a ng-class="{ 'current-page': window.location.pathname.indexOf(url) >= 0 }">{{url}}</a>
    

    Given your example urls I think this is better because href would include the scheme ('https' for example) as well so no match would pop up.

    You could of course replace indexOf(...) with an exact match, if that's more appropriate.

    It uses the fact that ng-class can take in a map from potential classes ('current-page') to expressions that are coerced to a boolean value after evaluation (e.g. the indexOf(...) expression). See these docs.