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.
Use element. classList. toggle() to toggle the specified class for the element.
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.
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 ...
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.
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' }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With