我正在尝试使用切换元素的类 ng-class
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为true,我希望ng-class是icon- autoscroll,如果为false,我希望它为icon-autoscroll-disabled
$scope.autoScroll
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提供的应该是使用的一种。对于三元运算符,这是最标准的(对我而言,最容易阅读)。解决方案是
Solution 3
<button class="btn" ng-click="autoScroll = !autoScroll"> <i ng-class="autoScroll ? 'icon-autoscroll' : 'icon-autoscroll-disabled'"></i> </button>
转换为:
if (autoScroll == true) ?// use类'icon-autoscroll' ://其他用法'icon- autoscroll-disabled'
if (autoScroll == true) ?
'icon-autoscroll' :
'icon- autoscroll-disabled'
如何在ng-class中使用条件:
解决方案1:
<i ng-class="{'icon-autoscroll': autoScroll, 'icon-autoscroll-disabled': !autoScroll}"></i>
<i ng-class="{true: 'icon-autoscroll', false: 'icon-autoscroll-disabled'}[autoScroll]"></i>
解决方案3(角度v.1.1.4 +引入了对三元运算符的支持):
<i ng-class="autoScroll ? 'icon-autoscroll' : 'icon-autoscroll-disabled'"></i>