Note that there are some explanatory texts on larger screens.

plurals
  1. POAngularJS toggle class using ng-class
    text
    copied!<p>I am trying to toggle the class of an element using <code>ng-class</code></p> <pre><code>&lt;button class="btn"&gt; &lt;i ng-class="{(isAutoScroll()) ? 'icon-autoscroll' : 'icon-autoscroll-disabled'}"&gt;&lt;/i&gt; &lt;/button&gt; </code></pre> <p>isAutoScroll():</p> <pre><code>$scope.isAutoScroll = function() { $scope.autoScroll = ($scope.autoScroll) ? false : true; return $scope.autoScroll; } </code></pre> <p>Basically, if <code>$scope.autoScroll</code> is true, I want ng-class to be <code>icon-autoscroll</code> and if its false, I want it to be <code>icon-autoscroll-disabled</code></p> <p>What I have now isn't working and is producing this error in the console</p> <p><code>Error: Lexer Error: Unexpected next character at columns 18-18 [?] in expression [{(isAutoScroll()) ? 'icon-autoscroll' : 'icon-autoscroll-disabled'}].</code></p> <p>How do I correctly do this?</p> <p><strong>EDIT</strong></p> <p>solution 1: (outdated)</p> <pre><code>&lt;button class="btn" ng-click="autoScroll = !autoScroll"&gt; &lt;i ng-class="{'icon-autoscroll': autoScroll, 'icon-autoscroll-disabled': !autoScroll}"&gt;&lt;/i&gt; &lt;/button&gt; </code></pre> <p><strong>EDIT 2</strong></p> <p>solution 2:</p> <p>I wanted to update the solution as <code>Solution 3</code>, 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</p> <pre><code>&lt;button class="btn" ng-click="autoScroll = !autoScroll"&gt; &lt;i ng-class="autoScroll ? 'icon-autoscroll' : 'icon-autoscroll-disabled'"&gt;&lt;/i&gt; &lt;/button&gt; </code></pre> <p>translates to:</p> <p><code>if (autoScroll == true) ?</code> //use class <code>'icon-autoscroll' :</code> //else use <code>'icon-autoscroll-disabled'</code></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload