简体   繁体   中英

How to set active state on page load with Angular

I have the following set of Bootstrap nav pills in my navigation bar. As you can see from my Angular 'ng-init' code I'm setting 'dateState to 'past' on page load. My problem is that my 'Past Events' nav pill is not highlighted on page load. I have to explicitly click the nav pills to get their 'active' highlight. How would I set whichever pill I have set in 'ng-init' to also show its active state on page load (there's a chance I'll be changing ng-init to 'future' or 'live' in the future so I don't want to just hard code the 'active' state)?

<ul class="nav nav-pills pull-right" ng-init="dateState='past'">
    <li><a href ng-click="dateState = 'live'">Live!</a></li>
    <li><a href ng-click="dateState = 'past'">Past Events</a></li>
    <li><a href ng-click="dateState = 'future'">Future Events</a></li>
</ul>

I was able to achieve what I was aiming for by changing my above code to the following:

<ul class="nav nav-pills pull-right" ng-init="dateState='past'">
    <li><a href ng-click="dateState = 'live'" ng-class="{'activeDate': dateState=='live'}">Live!</a></li>
    <li><a href ng-click="dateState = 'past'" ng-class="{'activeDate': dateState=='past'}">Past Events</a></li>
    <li><a href ng-click="dateState = 'future'" ng-class="{'activeDate': dateState=='future'}">Future Events</a></li>
</ul>

The class now becomes 'activeDate' whenever an 'li' item is active. I added the following very basic styling to test this:

a.activeDate {
    background-color: white;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM