I want to set css classes to items of a list depending of subelements matches a certain criterion or not. The structure is like in the following example:
<ul ng-controller="Navigation">
<li><a href="#">Category A</a>
<ul>
<li><a href="a1.html">a1</a></li>
<li><a href="a2.html">a2</a></li>
</ul>
</li>
<li><a href="#">Category B</a>
<ul>
<li><a href="b1.html">b1</a></li>
<li><a href="b2.html">b2</a></li>
</ul>
</li>
<li><a href="contact.html">contact</a></li>
</ul>
My model is the current page, say a2.html
. If a link has the same href
attribute as the model value, it should have a certain css class (active
). This could be done with this expression:
<a href="a1.html" ng-class="{'active': currentPage == 'a1.html'}>
But this is a bit inelegant, because I have to repeat the file name (a1.html
). Would it be possible to pass the current element to a function? Something like this: ng-class="getClass(currentElement)"
The next problem is, that I want to select parent elements depending on whether a child has the class active
or not. If <a href="a1.html">a1</a>
in my above example is selected, then Category A
should get the class active
too.
Conclusion
'stewie's solution works, but I came to the conclusion that Angular is not the best tool for this job. It is not a web 'application' (the domain of Angular) but static html which should be enriched a bit.
This simple jQuery snippet does the job:
var activeLink = $("a").filter(function() {
return $(this).attr("href") == currentPage();
});
activeLink.addClass("active");
activeLink.parents("li").children("a").addClass("active");