-1

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?

NodeDev
  • 43
  • 1
  • 7
  • Be aware that `window.location.href` will also include scheme ("http" or "https") in addition to host ("example.com") and pathname ("/home"). – Jeroen Aug 12 '18 at 16:59
  • @Adriani6 directives are not applicable here because here we wants to hide a class only and not the entire a element. – NodeDev Aug 12 '18 at 17:03
  • @NodeDev I have edited and suggested a more specific title, feel free to roll back or further update the title if it isn't what you're trying to ask. (The previous one was a bit too abstract to see what's being asked, I think.) – Jeroen Aug 12 '18 at 17:14

1 Answers1

0

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.

Jeroen
  • 60,696
  • 40
  • 206
  • 339