1

I am trying to create an ng-class that sets the tab class to "active" based on the current day of the week utilizing JavaScripts getDay() which applies numbers 0-6 to each day of the week. So if it's Monday, check the currentDay if it is equal to 1 apply class, if it's Tuesday's tab check the currentDay, if it is equal to 2 apply the class to tuesday, etc. e.g:

Javascript (I tried putting this into a $scope object in my controller but that didn't seem to work either):

var d = new Date();
var currentDay = d.getDay();

View

<ul class="nav nav-tabs">
 <li ng-class="{'active' : currentDay == 4}">
   <a href="schedule/#thursday" data-toggle="tab">
     <h2>Day 1 | Thursday</h2>
   </a>
 </li>
 <li>
   ...
 </li>
</ul>

I've tried multiple different ways to get this to work. If I check currentDay == 4 in the console (since today is Thursday) it comes back as 'true'. So the class should be applied. I also tried without the ' ' around active, and putting the condition in [ ]. Nothing seems to work.. Appreciate any input, thank you!

1
  • Show what did you add on controller. Commented Apr 25, 2014 at 4:56

2 Answers 2

2

Your code above works for me. Here is an example fiddle: http://jsfiddle.net/HB7LU/3252/

Controller:

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.currentDay = 4;
}

View:

<div ng-controller="MyCtrl">
    <ul class="nav nav-tabs">
        <li ng-class="{'active' : currentDay == 4}">
            <a href="schedule/#thursday" data-toggle="tab">
                <h2>Day 1 | Thursday</h2>
            </a>
        </li>
    </ul>
</div>

If I had to guess, you are not applying the value to the $scope correctly

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

2 Comments

Thanks @Matt Way for the reply! The thing is I didn't want to set a hard value in the controller for currentDay. I wanted it to check the actual day. JavaScript's getDay() returns numbers 0-6, with 0 being Sunday - 6 being Saturday. I was able to get it to work dynamically by checking the current day, will update with answer!
@satully89: I figured that showing it as a hardcoded value would make it easier to understand, and changing it trivial. Glad you found your answer.
1

I was able to figure it out!

So in the controller I added the last line below

var d = new Date();
var currentDay = d.getDay();
$scope.activeDay = currentDay;

and updated the view to read:

<li ng-class="{'active' : activeDay == 4}">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.