Switch class and text in angular.js
There is a lock and unlock function, which is presented in html
<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 a REST API call
$scope.unlock = function(user){
user.$unlock();
}
$scope.lock = function(user){
user.$lock();
}
How can I switch between two states in angular.js? I mean, when the lock is successful and successful, the first option should be hidden when the unlock button should be visible.
selectedUser.enabled
returns 1for unlock and 0for blocked.
+5
1 answer
Just use one liand set the class 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 rewritten as:
{{ selectedUser.enabled ? 'Lock' : 'Unlock' }}
+20