【发布时间】:2013-03-02 02:13:13
【问题描述】:
我正在尝试使用 ng-class 切换元素的类
<button class="btn">
<i ng-class="{(isAutoScroll()) ? 'icon-autoscroll' : 'icon-autoscroll-disabled'}"></i>
</button>
isAutoScroll():
$scope.isAutoScroll = function()
{
$scope.autoScroll = ($scope.autoScroll) ? false : true;
return $scope.autoScroll;
}
基本上,如果$scope.autoScroll 为真,我希望ng-class 为icon-autoscroll,如果为假,我希望它为icon-autoscroll-disabled
我现在所拥有的东西不起作用,并且在控制台中产生了这个错误
Error: Lexer Error: Unexpected next character at columns 18-18 [?] in expression [{(isAutoScroll()) ? 'icon-autoscroll' : 'icon-autoscroll-disabled'}].
我该如何正确地做到这一点?
编辑
解决方案 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 提供,应该是使用的解决方案。对于三元运算符(对我来说最容易阅读),它是最标准的。解决方案是
<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'
【问题讨论】:
-
can't use conditionals in
angular expressionsper docs => 无控制流语句:您不能在角度表达式中执行以下任何操作:条件、循环或抛出.使用另一个函数或指令 -
@Ronnie 我看到了你的解决方案,太酷了。但我想知道为什么这里的
autoScroll只会在每个按钮中起作用? (我用多个按钮对此进行了测试,效果也很好)我的意思是,当我单击每个按钮时,它只会影响那个按钮,而不是所有按钮。
标签: javascript angularjs