-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?

3
  • Be aware that window.location.href will also include scheme ("http" or "https") in addition to host ("example.com") and pathname ("/home"). Commented Aug 12, 2018 at 16:59
  • @Adriani6 directives are not applicable here because here we wants to hide a class only and not the entire a element. Commented Aug 12, 2018 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.) Commented Aug 12, 2018 at 17:14

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Can you please edit the answer for the updated array in question?
@NodeDev Updated my answer following your updated question.
Great! I appreciate your help

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.