问题描述
我正在尝试使用 ng-class
<button class="btn">
<i ng-class="{(isAutoScroll()) ? 'icon-autoscroll' : 'icon-autoscroll-disabled'}"></i>
</button>
isAutoScroll():
isAutoScroll():
$scope.isAutoScroll = function()
{
$scope.autoScroll = ($scope.autoScroll) ? false : true;
return $scope.autoScroll;
}
基本上,如果 $scope.autoScroll
为真,我希望 ng-class 为 icon-autoscroll
,如果为假,我希望它为 图标自动滚动禁用
Basically, if $scope.autoScroll
is true, I want ng-class to be icon-autoscroll
and if its false, I want it to be icon-autoscroll-disabled
我现在所拥有的无法正常工作并且在控制台中产生此错误
What I have now isn't working and is producing this error in the console
错误:词法分析器错误:表达式 [{(isAutoScroll()) 中第 18-18 列 [?] 处出现意外的下一个字符?'icon-autoscroll' : 'icon-autoscroll-disabled'}].
我该如何正确执行此操作?
How do I correctly do this?
编辑
解决方案1:(过时)
<button class="btn" ng-click="autoScroll = !autoScroll">
<i ng-class="{'icon-autoscroll': autoScroll, 'icon-autoscroll-disabled': !autoScroll}"></i>
</button>
编辑 2
解决方案 2:
我想更新解决方案,因为 Solution 3
由 Stewie 提供,应该是使用的那个.当涉及到三元运算符时,它是最标准的(对我来说也是最容易阅读的).解决办法是
I wanted to update the solution as Solution 3
, provided by Stewie, should be the one used. It is the most standard when it comes to ternary operator (and to me easiest to read). The solution would be
<button class="btn" ng-click="autoScroll = !autoScroll">
<i ng-class="autoScroll ? 'icon-autoscroll' : 'icon-autoscroll-disabled'"></i>
</button>
翻译成:
if (autoScroll == true) ?
//使用类 'icon-autoscroll' :
//否则使用 'icon-autoscroll-disabled'代码>
if (autoScroll == true) ?
//use class 'icon-autoscroll' :
//else use 'icon-autoscroll-disabled'
推荐答案
如何在 ng-class 中使用条件:
How to use conditional in ng-class:
解决方案 1:
<i ng-class="{'icon-autoscroll': autoScroll, 'icon-autoscroll-disabled': !autoScroll}"></i>
解决方案 2:
<i ng-class="{true: 'icon-autoscroll', false: 'icon-autoscroll-disabled'}[autoScroll]"></i>
解决方案 3(angular v.1.1.4+ 引入了对三元运算符的支持):
Solution 3 (angular v.1.1.4+ introduced support for ternary operator):
<i ng-class="autoScroll ? 'icon-autoscroll' : 'icon-autoscroll-disabled'"></i>
这篇关于使用 ng-class 的 AngularJS 切换类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!