Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle class and text in angular.js

There is a lock and unlock functionality, which in html is represented by

<li><a ng:click="lock(selectedUser)"><i class="icon-lock icon"></i>Lock</a></li>

and

<li><a ng:click="unlock(selectedUser)"><i class="icon-unlock icon"></i>UnLock</a></li>

Unlock/Lock is acutally a REST API call

$scope.unlock = function(user){
     user.$unlock();
}

$scope.lock = function(user){
     user.$lock();
}

How can I toggle between the two states in angular.js? I mean when a lock is performed and is successfull the first option should be hidden while the unlock button should get visible.

selectedUser.enabled

returns 1 for unlocked and 0 for locked.

like image 521
UpCat Avatar asked Apr 14 '13 02:04

UpCat


People also ask

How do you toggle classes in typescript?

Use element. classList. toggle() to toggle the specified class for the element.

What is toggle class in JavaScript?

The toggleClass() method toggles between adding and removing one or more class names from the selected elements. This method checks each element for the specified class names. The class names are added if missing, and removed if already set - This creates a toggle effect.

How do you toggle a class on an element?

Toggling the class means if there is no class name assigned to the element, then a class name can be assigned to it dynamically or if a certain class is already present, then it can be removed dynamically by just using the toggle() or by using contains(), add(), remove() methods of DOMTokenList object within JavaScript ...

Is there a toggle function in JavaScript?

In JavaScript toggle is one of the feature and it is used as default method for handling the hide() and show() for the selected elements.


1 Answers

Just use one li, and set the class with ng:class:

HTML:

<li>
  <a ng:click="toggleLock(selectedUser)">
    <i class="icon" ng:class="{ 'icon-lock': selectedUser.enabled, 'icon-unlock': ! selectedUser.enabled }"></i>
    {{ selectedUser.enabled && 'Lock' || 'Unlock' }}
  </a>
</li>

Javascript:

$scope.toggleLock = function (user) {
     user.enabled ? user.$lock() : user.$unlock();
}

Update: Angular 1.1.5 added support for ternary operators, so the above can be re-written as:

{{ selectedUser.enabled ? 'Lock' : 'Unlock' }}
like image 80
Joseph Silber Avatar answered Sep 28 '22 06:09

Joseph Silber