AngularJS 模板中的 if else 语句

if else statement in AngularJS templates

提问人:vzhen 提问时间:4/4/2013 最后编辑:dpassagevzhen 更新时间:11/14/2021 访问量:1202699

问:

我想在 AngularJS 模板中做一个条件。我从 Youtube API 获取视频列表。有些视频是 16:9 的比例,有些是 4:3 的比例。

我想做一个这样的条件:

if video.yt$aspectRatio equals widescreen then 
    element's attr height="270px"
else
    element's attr height="360px"

我正在使用 .不知道这种情况我应该怎么做:ng-repeat

  • 在作用域中添加函数?
  • 在模板中做?
if 语句 angularjs

评论

2赞 virender 9/25/2015
我在这里找到了一篇 ng-if 文章。goo.gl/wQ30uf

答:

1327赞 Amyth 4/4/2013 #1

Angularjs(低于 1.1.5 的版本)不提供 功能。以下是要考虑实现的目标的几个选项:if/else

(如果您使用的是 1.1.5 或更高版本,请跳转到下面的更新 (#2))

1. 三元运算符:

正如@Kirk在评论中建议的那样,最干净的方法是使用三元运算符,如下所示:

<span>{{isLarge ? 'video.large' : 'video.small'}}</span>

2. ng-switch指令:

可以使用如下所示。

<div ng-switch on="video">
    <div ng-switch-when="video.large">
        <!-- code to render a large video block-->
    </div>
    <div ng-switch-default>
        <!-- code to render the regular video block -->
    </div>
</div>

3. ng-hide / ng-show 指令

或者,您也可以使用,但使用它实际上会同时渲染一个大视频和一个小视频元素,然后隐藏满足条件的元素并显示满足条件的元素。因此,在每个页面上,您实际上将渲染两个不同的元素。ng-show/ng-hideng-hideng-show

4. 另一个可以考虑的选择是 ng-class 指令。

这可以按如下方式使用。

<div ng-class="{large-video: video.large}">
    <!-- video block goes here -->
</div>

上面基本上会在 div 元素中添加一个 css 类,如果是真的。large-videovideo.large

更新:Angular 1.1.5 引入了 ngIf 指令

5. NG-IF指令:

在上述版本中,您可以使用该指令。如果提供的表达式返回,这将删除该元素,如果表达式返回,则在 DOM 中重新插入 。可以按如下方式使用。1.1.5ng-iffalseelementtrue

<div ng-if="video == video.large">
    <!-- code to render a large video block-->
</div>
<div ng-if="video != video.large">
    <!-- code to render the regular video block -->
</div>

评论

10赞 czerasz 7/8/2013
它应该是ng-switch on="video"ng-switch-on="video"
4赞 falko 12/3/2013
这是怎么做到的?if(){} else if(){} else if(){} else {} 但是在 dom 中只包含一个元素
211赞 Kirk Strobeck 1/26/2014
也是三元<span>{{isAdded ? 'Added' : 'Add to cart'}}</span>
18赞 Wilhelm Murdoch 6/17/2014
请记住,在 DOM 的条件计算结果为 之前,不会将封闭的元素添加到 中,这与 和 不同。ng-iftrueng-hideng-show
1赞 Sami 7/15/2015
为什么不简单地?有问题吗?还是之前不可用?对我来说,它工作得很好ng-switch="video"
30赞 Noah Freitas 4/5/2013 #2

您可以通过将属性传递到筛选器,并将结果绑定到模板中的 height 属性来直接使用属性。video.yt$aspectRatio

您的过滤器将如下所示:

app.filter('videoHeight', function () {
  return function (input) {
    if (input === 'widescreen') {
      return '270px';
    } else {
      return '360px';
    }
  };
});

模板将是:

<video height={{video.yt$aspectRatio | videoHeight}}></video>

评论

0赞 Fractaliste 3/31/2014
当您的代码为空或未定义时,您的代码怎么样?是否可以应用默认值?video.yt$aspectRatio
182赞 Brian Genisio 7/10/2013 #3

在最新版本的 Angular 中(从 1.1.5 开始),它们包含一个名为 .它与元素不同,元素没有被隐藏,但根本不包含在 DOM 中。它们对于创建成本高但未使用的组件非常有用:ngIfngShowngHide

<div ng-if="video == video.large">
    <!-- code to render a large video block-->
</div>
<div ng-if="video != video.large">
    <!-- code to render the regular video block -->
</div>

评论

6赞 David Salamon 7/12/2016
Keep in mind that introduces an isolated scope, so that becomes in the body of .ng-if$parent$parent.$parentng-if
13赞 Spock 10/29/2013 #4

In this case you want to "calculate" a pixel value depending of an object property.

I would define a function in the controller that calculates the pixel values.

In the controller:


$scope.GetHeight = function(aspect) {
   if(bla bla bla) return 270;
   return 360;
}

Then in your template you just write:


element height="{{ GetHeight(aspect) }}px "

145赞 Oliver Dixon 9/5/2014 #5

Ternary is the most clear way of doing this.

<div>{{ConditionVar ? 'varIsTrue' : 'varIsFalse'}}</div>

评论

1赞 YoBre 5/6/2015
Ho to do this with 2 condition in or?? like <div>{{A==B || A==C ? 'varIsTrue' : 'varIsFalse'}}</div>
2赞 Oliver Dixon 5/22/2015
Wrap it (A==B || A==C)
1赞 sksallaj 9/24/2015
love this answer! Using ng- directives gives lots of html whitespace if a div doesn't satisfy the condition..
52赞 lpappone 10/4/2014 #6

Angular itself doesn't provide if/else functionality, but you can get it by including this module:

https://github.com/zachsnow/ng-elif

In its own words, it's just "a simple collection of control flow directives: ng-if, ng-else-if, and ng-else." It's easy and intuitive to use.

Example:

<div ng-if="someCondition">
    ...
</div>
<div ng-else-if="someOtherCondition">
    ...
</div>
<div ng-else>
    ...
</div>

评论

1赞 1/19/2017
i dont want to repeat the code in div again and again.
1赞 Zach Snow 5/13/2017
You don't have to repeat anything -- you could as easily do . Perhaps I misunderstand? (I wrote that module -- it should work just like and in JS).ng-if="someCondition && someOtherCondition"ifelse
1赞 Nico Westerdale 8/2/2017
This is an absolute lifesaver. This should be part of Angular core, it's indispensable in template coding. Way cleaner than having ternary operators all over the place, and overcomes the limitations of ng-switch not being able to evaluate expressions.
0赞 Zach Snow 10/29/2017
Thanks @NicoWesterdale! Also, I added a richer version of ng-switch you might find useful: github.com/zachsnow/ng-cases
11赞 Tom Stickel 7/24/2015 #7

I agree that a ternary is extremely clean. Seems that it is very situational though as somethings I need to display div or p or table , so with a table I don't prefer a ternary for obvious reasons. Making a call to a function is typically ideal or in my case I did this:

<div ng-controller="TopNavCtrl">
        <div ng-if="info.host ==='servername'">
            <table class="table">
                <tr ng-repeat="(group, status) in user.groups">
                    <th style="width: 250px">{{ group }}</th>
                    <td><input type="checkbox" ng-model="user.groups[group]" /></td>
                </tr>
            </table>
        </div>
       <div ng-if="info.host ==='otherservername'">
            <table class="table">
                <tr ng-repeat="(group, status) in user.groups">
                    <th style="width: 250px">{{ group }}</th>
                    <td><input type="checkbox" ng-model="user.groups[group]" /></td>
                </tr>
            </table>
        </div>
</div>
4赞 JBhardwaj 12/8/2016 #8
    <div ng-if="modeldate==''"><span ng-message="required" class="change">Date is required</span> </div>

you can use the ng-if directive as above.

3赞 Jan Clemens Stoffregen 10/9/2017 #9

A possibility for Angular: I had to include an if - statement in the html part, I had to check if all variables of an URL that I produce are defined. I did it the following way and it seems to be a flexible approach. I hope it will be helpful for somebody.

The html part in the template:

    <div  *ngFor="let p of poemsInGrid; let i = index" >
        <a [routerLink]="produceFassungsLink(p[0],p[3])" routerLinkActive="active">
    </div>

And the typescript part:

  produceFassungsLink(titel: string, iri: string) {
      if(titel !== undefined && iri !== undefined) {
         return titel.split('/')[0] + '---' + iri.split('raeber/')[1];
      } else {
         return 'Linkinformation has not arrived yet';
      }
  }

Thanks and best regards,

Jan

评论

3赞 pzaenger 10/9/2017
Looks more like Angular than AngularJS.
0赞 Jan Clemens Stoffregen 10/9/2017
@pzaenger, yes, but many answers for this question work for both, so I think some people, like myself, look at the answers anyway. Please let me know if you mind.
3赞 pzaenger 10/9/2017
Well. At least you should mention this in your answer.
0赞 Jan Clemens Stoffregen 10/9/2017
@pzaenger, thank you for this hint, I mentioned it now.
0赞 ggorlen 5/8/2023
Angular and AngularJS are totally different. This belongs elsewhere.
1赞 Aamir Anwar 3/3/2020 #10

ng If else statement

ng-if="receiptData.cart == undefined ? close(): '' ;"