最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Toggle class and text in angular.js - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited Apr 14, 2013 at 3:36 Joseph Silber 220k59 gold badges368 silver badges293 bronze badges asked Apr 14, 2013 at 2:41 DarkLeafyGreenDarkLeafyGreen 70.4k134 gold badges390 silver badges614 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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' }}
发布评论

评论列表(0)

  1. 暂无评论