5

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.

1 Answer 1

20

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' }}
Sign up to request clarification or add additional context in comments.

2 Comments

@artworkadシ - I changed my answer to reflect your clarified question.
Thank you that works. Can I change the text "Lock" to "Unlock" the same way?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.