Reputation: 9247
I have this:
<div class="account-item">
<div class="account-heading" ng-class="active">
<h4 class="account-title">
<a href="#/Messages" onclick="SetActiveAccountHeading(this);">
7. @Translate("SYSTEM_MESSAGES")</a>
</h4>
</div>
</div>
<div class="account-item">
<div class="account-heading" ng-class="active">
<h4 class="account-title">
<a href="#/Info" onclick="SetActiveAccountHeading(this);">
7. @Translate("SYSTEM_INFO")</a>
</h4>
</div>
</div>
In angular i have this:
$scope.active = "active";
but how can i change this on click so if user click on menu once it would be active if again click it would be NOT active?
Upvotes: 18
Views: 91040
Reputation: 21901
Ok say you have multiple menu items and you want to toggle the class according to click,
you can create a array in the controller which represents the menu items as,
$scope.menuItems = ['Home', 'Contact', 'About', 'Other'];
assign the default selected ,menu item
$scope.activeMenu = $scope.menuItems[0];
create a function to assign the selected Menu value, this function will assign the $scope.activeMenu
a last selected menu item.
$scope.setActive = function(menuItem) {
$scope.activeMenu = menuItem
}
in HTML
loop through the menuItems
array and create the menu.
in the ng-class
check last clicked menu item is equal to item in the repeat.
if click on the menu then call setActive()
function in the controller and pass the menu item name as an argument.
<div class="account-item" ng-repeat='item in menuItems'>
<div class="account-heading" ng-class="{active : activeMenu === item}">
<h4 class="account-title">
<a href="#/Messages" ng-click="setActive(item)"> {{ item }}</a>
</h4>
</div>
</div>
here is the DEMO
here is a DEMO without ng-repeat
Upvotes: 48
Reputation: 642
Angular4:
<a routerLink="/user/bob" routerLinkActive="active-link">Bob</a>
<a [routerLink]="['calendar']" routerLinkActive="active">
Documentation: https://angular.io/api/router/RouterLinkActive
Upvotes: 6
Reputation: 809
If you are using [ui-router] you not need to write anything just you have add this ui-sref-active="active-menu" property in your tag which you want to active after click/navigate.
Upvotes: 5
Reputation: 1853
For cleaner code try this:
<div class="account-item" ng-init="active = true">
<div class="account-heading" ng-class="{'active': active}">
<h4 class="account-title">
<a href="#/Messages" ng-click="active = !active">7. @Translate("SYSTEM_MESSAGES")</a>
</h4>
</div>
</div>
You can remove the onclick event SetActiveAccountHeading(this);.
Here's the JsFiddle link.
You can view the result in the developer's console.
Hope it helps.
Upvotes: 2
Reputation: 2787
This is what you need.
<div class="account-item" ng-init="active = true">
<div class="account-heading" ng-class="{'active': active === true}" ng-click="active = !active">
<h4 class="account-title">
<a href="#/Messages">7. @Translate("SYSTEM_MESSAGES")</a>
</h4>
</div>
</div>
No other scripting. +1 if it helps.
Upvotes: 11