DarkLeafyGreen
DarkLeafyGreen

Reputation: 70416

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.

Upvotes: 5

Views: 9757

Answers (1)

Joseph Silber
Joseph Silber

Reputation: 219938

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' }}

Upvotes: 20

Related Questions