I am trying to toggle the class of an element using 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;
}
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
Error: Lexer Error: Unexpected next character at columns 18-18 [?] in expression [{(isAutoScroll()) ? 'icon-autoscroll' : 'icon-autoscroll-disabled'}].
How do I correctly do this?
EDIT
solution 1: (outdated)
<button class="btn" ng-click="autoScroll = !autoScroll">
<i ng-class="{'icon-autoscroll': autoScroll, 'icon-autoscroll-disabled': !autoScroll}"></i>
</button>
EDIT 2
solution 2:
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>
translates to:
if (autoScroll == true) ? //use class 'icon-autoscroll' : //else use 'icon-autoscroll-disabled'
angular expressionsper docs => No Control Flow Statements: you cannot do any of the following in angular expression: conditionals, loops, or throw. Use another function or directiveautoScrollhere will just effect in each button ? (I tested this with multiple buttons, and it works well too) I mean, when I click each button, it effect just that button, instead of all buttons.