Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

javascript - AngularJS使用ng-class切换类(AngularJS toggle class using ng-class)

I am trying to toggle the class of an element using ng-class

(我试图使用ng-class切换元素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;
}

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

(基本上,如果$scope.autoScroll为true,我希望ng-class为icon-autoscroll ,如果为false,我希望它为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)

(解决方案1 ??:(过时))

<button class="btn" ng-click="autoScroll = !autoScroll">
  <i ng-class="{'icon-autoscroll': autoScroll, 'icon-autoscroll-disabled': !autoScroll}"></i>
</button>

EDIT 2

(编辑2)

solution 2:

(解决方案2:)

I wanted to update the solution as Solution 3 , provided by Stewie, should be the one used.

(我想更新解决Solution 3 ,因为Stewie提供的解决Solution 3应该是使用的解决Solution 3 。)

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'

(//使用'icon-autoscroll' : //否则使用'icon-autoscroll-disabled')

  ask by Ronnie translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How to use conditional in ng-class:

(如何在ng-class中使用条件:)

Solution 1:

(解决方案1:)

<i ng-class="{'icon-autoscroll': autoScroll, 'icon-autoscroll-disabled': !autoScroll}"></i>

Solution 2:

(解决方案2:)

<i ng-class="{true: 'icon-autoscroll', false: 'icon-autoscroll-disabled'}[autoScroll]"></i>

Solution 3 (angular v.1.1.4+ introduced support for ternary operator):

(解决方案3(角度v.1.1.4 +引入了对三元运算符的支持):)

<i ng-class="autoScroll ? 'icon-autoscroll' : 'icon-autoscroll-disabled'"></i>

Plunker

(Plunker)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...