ChatGPT解决这个技术问题 Extra ChatGPT

if else statement in AngularJS templates

I want to do a condition in an AngularJS template. I fetch a video list from the Youtube API. Some of the videos are in 16:9 ratio and some are in 4:3 ratio.

I want to make a condition like this:

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

I'm iterating the videos using ng-repeat. Have no idea what should I do for this condition:

Add a function in the scope?

Do it in template?

I found one ng-if articles here. goo.gl/wQ30uf

M
Mbengue Assane

Angularjs (versions below 1.1.5) does not provide the if/else functionality . Following are a few options to consider for what you want to achieve:

(Jump to the update below (#5) if you are using version 1.1.5 or greater)

1. Ternary operator:

As suggested by @Kirk in the comments, the cleanest way of doing this would be to use a ternary operator as follows:

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

2. ng-switch directive:

can be used something like the following.

<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 directives

Alternatively, you might also use ng-show/ng-hide but using this will actually render both a large video and a small video element and then hide the one that meets the ng-hide condition and shows the one that meets ng-show condition. So on each page you'll actually be rendering two different elements.

4. Another option to consider is ng-class directive.

This can be used as follows.

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

The above basically will add a large-video css class to the div element if video.large is truthy.

UPDATE: Angular 1.1.5 introduced the ngIf directive

5. ng-if directive:

In the versions above 1.1.5 you can use the ng-if directive. This would remove the element if the expression provided returns false and re-inserts the element in the DOM if the expression returns true. Can be used as follows.

<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>

It should be ng-switch on="video" instead ng-switch-on="video"
How do that? if(){} else if(){} else if(){} else {} But include in dom only one element
Also ternary <span>{{isAdded ? 'Added' : 'Add to cart'}}</span>
Keep in mind that ng-if will NOT add the enclosed elements to the DOM until its condition evaluates to true, unlike ng-hide and ng-show.
Why not simply ng-switch="video"? Some problem? or it was not available earlier? For me it it is working quite fine
B
Brian Genisio

In the latest version of Angular (as of 1.1.5), they have included a conditional directive called ngIf. It is different from ngShow and ngHide in that the elements aren't hidden, but not included in the DOM at all. They are very useful for components which are costly to create but aren't used:

<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>

Keep in mind that ng-if introduces an isolated scope, so that $parent becomes $parent.$parent in the body of ng-if.
O
Oliver Dixon

Ternary is the most clear way of doing this.

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

Ho to do this with 2 condition in or?? like
{{A==B || A==C ? 'varIsTrue' : 'varIsFalse'}}
Wrap it (A==B || A==C)
love this answer! Using ng- directives gives lots of html whitespace if a div doesn't satisfy the condition..
f
fracz

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>

i dont want to repeat the code in div again and again.
You don't have to repeat anything -- you could as easily do ng-if="someCondition && someOtherCondition". Perhaps I misunderstand? (I wrote that module -- it should work just like if and else in JS).
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.
Thanks @NicoWesterdale! Also, I added a richer version of ng-switch you might find useful: github.com/zachsnow/ng-cases
N
Noah Freitas

You could use your video.yt$aspectRatio property directly by passing it through a filter, and binding the result to the height attribute in your template.

Your filter would look something like:

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

And the template would be:

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

How about your code when video.yt$aspectRatio is empty or undefined? Is it possible to apply a default value?
S
Spock

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 "


T
Tom Stickel

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>

J
JBhardwaj
    <div ng-if="modeldate==''"><span ng-message="required" class="change">Date is required</span> </div>

you can use the ng-if directive as above.


J
Jan Clemens Stoffregen

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


Looks more like Angular than AngularJS.
@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.
Well. At least you should mention this in your answer.
@pzaenger, thank you for this hint, I mentioned it now.
A
Aamir Anwar

ng If else statement

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