Javascript AngularJS 模板中的三元运算符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12008580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:53:00  来源:igfitidea点击:

Ternary operator in AngularJS templates

javascripthtmlangularjsternary-operator

提问by cricardol

How do you do a ternary with AngularJS (in the templates)?

你如何用 AngularJS(在模板中)做一个三元组?

It would be nice to use some in html attributes (classes and style) instead of creating and calling a function of the controller.

最好在 html 属性(类和样式)中使用一些,而不是创建和调用控制器的函数。

回答by Mark Rajcok

Update: Angular 1.1.5 added a ternary operator, so now we can simply write

更新:Angular 1.1.5 添加了一个三元运算符,所以现在我们可以简单地编写

<li ng-class="$first ? 'firstRow' : 'nonFirstRow'">


If you are using an earlier version of Angular, your two choices are:

如果您使用的是早期版本的 Angular,您有两种选择:

  1. (condition && result_if_true || !condition && result_if_false)
  2. {true: 'result_if_true', false: 'result_if_false'}[condition]
  1. (condition && result_if_true || !condition && result_if_false)
  2. {true: 'result_if_true', false: 'result_if_false'}[condition]

item 2. above creates an object with two properties. The array syntax is used to select either the property with name true or the property with name false, and return the associated value.

上面的第 2 项创建了一个具有两个属性的对象。数组语法用于选择名称为 true 的属性或名称为 false 的属性,并返回关联的值。

E.g.,

例如,

<li class="{{{true: 'myClass1 myClass2', false: ''}[$first]}}">...</li>
 or
<li ng-class="{true: 'myClass1 myClass2', false: ''}[$first]">...</li>

$first is set to true inside an ng-repeat for the first element, so the above would apply class 'myClass1' and 'myClass2' only the first time through the loop.

$first 在第一个元素的 ng-repeat 中设置为 true,因此上述内容仅在第一次通过循环时应用类“myClass1”和“myClass2”。

With ng-classthere is an easier way though: ng-class takes an expression that must evaluate to one of the following:

但是,使用ng-class有一种更简单的方法:ng-class 采用一个表达式,该表达式必须计算为以下之一:

  1. a string of space-delimited class names
  2. an array of class names
  3. a map/object of class names to boolean values.
  1. 一串空格分隔的类名
  2. 类名数组
  3. 类名到布尔值的映射/对象。

An example of 1) was given above. Here is an example of 3, which I think reads much better:

上面给出了 1) 的一个例子。这是 3 的一个例子,我认为它读起来要好得多:

 <li ng-class="{myClass: $first, anotherClass: $index == 2}">...</li>

The first time through an ng-repeat loop, class myClass is added. The 3rd time through ($index starts at 0), class anotherClass is added.

第一次通过 ng-repeat 循环,类 myClass 被添加。第三次通过($index 从 0 开始),添加了 anotherClass 类。

ng-styletakes an expression that must evaluate to a map/object of CSS style names to CSS values. E.g.,

ng-style采用一个表达式,该表达式必须计算为 CSS 样式名称到 CSS 值的映射/对象。例如,

 <li ng-style="{true: {color: 'red'}, false: {}}[$first]">...</li>

回答by cricardol

Update:Angular 1.1.5 added a ternary operator, this answer is correct only to versions preceding 1.1.5. For 1.1.5 and later, see the currently accepted answer.

更新:Angular 1.1.5 添加了一个三元运算符,此答案仅适用于 1.1.5 之前的版本。对于 1.1.5 及更高版本,请参阅当前接受的答案。

Before Angular 1.1.5:

在 Angular 1.1.5 之前:

The form of a ternary in angularjs is:

angularjs中三元的形式是:

((condition) && (answer if true) || (answer if false))

An example would be:

一个例子是:

<ul class="nav">
    <li>
        <a   href="#/page1" style="{{$location.path()=='/page2' && 'color:#fff;' || 'color:#000;'}}">Goals</a>
    </li>
    <li>
        <a   href="#/page2" style="{{$location.path()=='/page2' && 'color:#fff;' || 'color:#000;'}}">Groups</a>
    </li>
</ul>

or:

或者:

 <li  ng-disabled="currentPage == 0" ng-click="currentPage=0"  class="{{(currentPage == 0) && 'disabled' || ''}}"><a> << </a></li>

回答by Ikrom

For texts in angular template (userTypeis property of $scope, like $scope.userType):

对于 angular 模板中的文本(userType是 $scope 的属性,如 $scope.userType):

<span>
  {{userType=='admin' ? 'Edit' : 'Show'}}
</span>

回答by Jan

By now we all found out version 1.1.5comes with a proper ternary in the $parsefunction so just use this answer as an example of filters:

到目前为止,我们都发现1.1.5版在$parse函数中带有适当的三元组,因此只需将此答案用作过滤器示例:

angular.module('myApp.filters', [])

  .filter('conditional', function() {
    return function(condition, ifTrue, ifFalse) {
      return condition ? ifTrue : ifFalse;
    };
  });

And then use it as

然后将其用作

<i ng-class="checked | conditional:'icon-check':'icon-check-empty'"></i>

回答by Aleksander Blomsk?ld

While you can use the condition && if-true-part || if-false-part-syntax in older versions of angular, the usual ternary operator condition ? true-part : false-partis available in Angular 1.1.5 and later.

虽然您可以condition && if-true-part || if-false-part在旧版本的 angular 中使用-syntax,但通常的三元运算符condition ? true-part : false-partAngular 1.1.5 及更高版本中可用。

回答by lionroots

There it is : ternary operator got added to angular parser in 1.1.5! see the changelog

就是这样:三元运算符在1.1.5 中被添加到角度解析器中!查看变更日志

Here is a fiddleshowing new ternary operator used in ng-class directive.

这是一个小提琴,显示了 ng-class 指令中使用的新三元运算符。

ng-class="boolForTernary ? 'blue' : 'red'"

回答by Zahid Rahman

  <body ng-app="app">
  <button type="button" ng-click="showme==true ? !showme :showme;message='Cancel Quiz'"  class="btn btn-default">{{showme==true ? 'Cancel Quiz': 'Take a Quiz'}}</button>
    <div ng-show="showme" class="panel panel-primary col-sm-4" style="margin-left:250px;">
      <div class="panel-heading">Take Quiz</div>
      <div class="form-group col-sm-8 form-inline" style="margin-top: 30px;margin-bottom: 30px;">

        <button type="button" class="btn btn-default">Start Quiz</button>
      </div>
    </div>
  </body>

Button toggle and change header of button and show/hide div panel. See the Plunkr

按钮切换和更改按钮的标题和显示/隐藏 div 面板。见Plunkr