user3684399
user3684399

Reputation: 165

Check if Class exists through the DOM using Angular

I have a bunch of pages following the same layout but some of them have a "secondary" navigation bar at the top. When this navigation bar exists I have to push the main content down from the page using margin-top in the less.

My issue is I can't find a clean way of doing this just through the DOM.

sample.html

<!-- The secondary navigation below the header -->
<div class="navigation-row text-center">
    <div class="col-xs-offset-2 col-xs-8 text-center">
        <h4> Sample Page </h4>
    </div>
</div>

<!-- Main Content -->
<div class="row">
    ...

index.html (inherited template that every page uses)

<!-- Main Content -->
<div class="content container-fluid">
    <div ng-class="{'secondary-nav' : document.getElementsByClassName('navigation-row').length > 0}" ui-view="main"></div>
</div>

So basically in my main content section I am trying to check if the class navigation-row exists on the page (navigation-row is the class for the secondary navbar) and if it does then add the class secondary-navbar-padding to the div.

I have tried using angular.element which looks like

<div class="row" ng-class="angular.element($document).hasClass('navigation-row') ? 'secondary-navbar-padding' : ''">

but it didn't work. Is this even possible to do? Am I approaching this incorrectly or if there is a suggestion for a better cleaner way to do this I would be open to do that also.

Upvotes: 2

Views: 10677

Answers (1)

Joe Beuckman
Joe Beuckman

Reputation: 2296

I think you are only checking if the document element itself has that class.

You can count the number of elements with that class like this:

document.getElementsByClassName('navigation-row').length

So you could use ng-class this way:

<div class="row" ng-class="{'secondary-navbar-padding' : document.getElementsByClassName('navigation-row').length > 0}">

Upvotes: 4

Related Questions