I am working on a Single page app website and I need the menu tab to change its class to active when a specific page is selected. The issue arises in my home.html template where I have an <a>
tag linking to the history page. The goal is for the history menu item to have an active class when this link is clicked. Initially, it works fine when the site is first loaded, but subsequent attempts do not result in the expected behavior if the user navigates back and forth between the history page and the home page. Any suggestions?
Please note that both the menu and the home content are templates that have been included using ng-include and ui-view (via ui-router).
<body onresize="setWidth()" ng-app="app" ng-controller="changeTab">
<div data-role="page" >
<!--include the menuTemplate set the current index to appropriate value-->
<div ng-include="'templates/menuTemplate.html'"></div>
</div>
<div data-role="main" class="ui-content">
<div ui-view></div>
</div>
</body>
menuTemplate.html:
<nav class="navbar navbar-default" id="desktopNav">
<div class="container-fluid">
<div class="topNav">
<ul class="nav navbar-nav">
<li ng-click="setIndex(0)" ng-class="(index==0)? 'active':''"><a id="homeButton" ui-sref="home">Home</a></li>
<li ng-click="setIndex(1)" ng-class="(index==1)? 'active':''"><a ui-sref="history">History</a></li>
<li ng-click="setIndex(2)" ng-class="(index==2)? 'active':''"><a ui-sref="ensembles">Ensembles</a></li>
<li ng-click="setIndex(3)" ng-class="(index==3)? 'active':''"><a ui-sref="staffs">Staffs</a></li>
<li ng-click="setIndex(4)" ng-class="(index==4)? 'active':''"><a ui-sref="career">Career</a></li>
<li ng-click="setIndex(5)" ng-class="(index==5)? 'active':''"><a ui-sref="contact">Contact</a></li>
</ul>
</div>
</div>
</nav>
home.html (VIEW) template:
<p><a href="history" ng-click="setIndex(1)">Learn more...</a></p>
Angular JS:
angular.module('app').controller('changeTab',['$scope', function($scope){
$scope.index;
$scope.setIndex = function(val){
$scope.index=val;
}
$scope.getIndex = function(val){
return $scope.index;
}
}]);