ChatGPT解决这个技术问题 Extra ChatGPT

inline conditionals in angular.js

I was wondering if there is a way in angular to conditionally display content other than using ng-show etc. For example in backbone.js I could do something with inline content in a template like:

<% if (myVar === "two") { %> show this<% } %>

but in angular, I seem to be limited to showing and hiding things wrapped in html tags

<p ng-hide="true">I'm hidden</p>
<p ng-show="true">I'm shown</p>

What is the recommended way in angular to conditionally show and hide inline content in angular just using {{}} rather than wrapping the content in html tags?

please unaccept my answer an accept 2Toad's when you get a chance.

2
2Toad

Angular 1.1.5 added support for ternary operators:

{{myVar === "two" ? "it's true" : "it's false"}}

This answer with the most upvotes should appear at the top of the answers... it's by far the most correct
user1469779 consider accepting this answer as this is the recommended way of achieving what you want for quite some time
@2Toad, my answer was old. this is the correct answer now, I don't know if the user will be back to "accept" it now, but I've annotated my answer as such. Such is the changing face of software development.
Thanks. How can I have it display the value of myVar only if it is false? (i.e. how can I nest variables in the expression?) I tried with {{myVar === "two" ? "it's true" : {{myVar}}}} but it doesn't work.
@Josh the myVar property doesn't need to be wrapped in additional curly braces, it's already inside an expression. Try {{myVar === "two" ? "it's true" : myVar}}
C
Community

EDIT: 2Toad's answer below is what you're looking for! Upvote that thing

If you're using Angular <= 1.1.4 then this answer will do:

One more answer for this. I'm posting a separate answer, because it's more of an "exact" attempt at a solution than a list of possible solutions:

Here's a filter that will do an "immediate if" (aka iif):

app.filter('iif', function () {
   return function(input, trueValue, falseValue) {
        return input ? trueValue : falseValue;
   };
});

and can be used like this:

{{foo == "bar" | iif : "it's true" : "no, it's not"}}

Thank you blesh, this is what I was going for. However I notice that if I try to put an html tag in one of the values it breaks: {{thing.second == "two" | iif : "
    " : "
      "}} I realize that there may be better ways to do this in angular, but is there a way to escape "<" and ">" so that tags can be output as part of the string?
ngBind doesn't allow HTML output, you'd want to use ng-bind-html-unsafe
The example of ng-binf-html-unsafe in the angular documentation uses it within a tag, for example . it may not be possible to do what I am trying to do inline.
IIF is the abbreviation for "Inline If". It's common in different programming languages... just not as common as ?: inline ifs. ;)
@BenLesh major props for editing your answer now that there's other options, good work.
B
Ben Lesh

Thousands of ways to skin this cat. I realize you're asking about between {{}} speifically, but for others that come here, I think it's worth showing some of the other options.

function on your $scope (IMO, this is your best bet in most scenarios):

  app.controller('MyCtrl', function($scope) {
      $scope.foo = 1;

      $scope.showSomething = function(input) {
           return input == 1 ? 'Foo' : 'Bar';
      };
   });

 <span>{{showSomething(foo)}}</span>

ng-show and ng-hide of course:

 <span ng-show="foo == 1">Foo</span><span ng-hide="foo == 1">Bar</span>

ngSwitch

 <div ng-switch on="foo">
   <span ng-switch-when="1">Foo</span>
   <span ng-switch-when="2">Bar</span>
   <span ng-switch-default>What?</span>
 </div>

A custom filter as Bertrand suggested. (this is your best choice if you have to do the same thing over and over)

app.filter('myFilter', function() {
   return function(input) {
     return input == 1 ? 'Foo' : 'Bar';
   }
}

{{foo | myFilter}}

Or A custom directive:

app.directive('myDirective', function() {
   return {
     restrict: 'E',
     replace: true,
     link: function(scope, elem, attrs) {
       scope.$watch(attrs.value, function(v) {
          elem.text(v == 1 ? 'Foo': 'Bar');
       });
     }
   };
});


<my-directive value="foo"></my-directive>

Personally, in most cases I'd go with a function on my scope, it keeps the markup pretty clean, and it's quick and easy to implement. Unless, that is, you're going to be doing the same exact thing over and over again, in which case I'd go with Bertrand's suggestion and create a filter or possibly a directive, depending on the circumstances.

As always, the most important thing is that your solution is easy to maintain, and is hopefully testable. And that is going to depend completely on your specific situation.


A
Ashley Davis

I am using the following to conditionally set the class attr when ng-class can't be used (for example when styling SVG):

ng-attr-class="{{someBoolean && 'class-when-true' || 'class-when-false' }}"

The same approach should work for other attribute types.

(I think you need to be on latest unstable Angular to use ng-attr-, I'm currently on 1.1.4)

I have published an article on working with AngularJS+SVG that talks about this and related issues. http://www.codeproject.com/Articles/709340/Implementing-a-Flowchart-with-SVG-and-AngularJS


e
ezequielc

For checking a variable content and have a default text, you can use:

<span>{{myVar || 'Text'}}</span>

thank you! I was trying this but I misses the quotes around the string :-)
For whatever reason, this syntax does not work using one time bindings.. {{::myVar || 'Text'}} will not work. Must be without the ::
B
Bertrand

If I understood you well I think you have two ways of doing it.

First you could try ngSwitch and the second possible way would be creating you own filter. Probably ngSwitch is the right aproach but if you want to hide or show inline content just using {{}} filter is the way to go.

Here is a fiddle with a simple filter as an example.

<div ng-app="exapleOfFilter">
  <div ng-controller="Ctrl">
    <input ng-model="greeting" type="greeting">
      <br><br>
      <h1>{{greeting|isHello}}</h1>
  </div>
</div>

angular.module('exapleOfFilter', []).
  filter('isHello', function() {
    return function(input) {
      // conditional you want to apply
      if (input === 'hello') {
        return input;
      }
      return '';
    }
  });

function Ctrl($scope) {
  $scope.greeting = 'hello';
}

J
JQuery Guru

Angular UI library has built-in directive ui-if for condition in template/Views upto angular ui 1.1.4

Example: Support in Angular UI upto ui 1.1.4

<div ui-if="array.length>0"></div>

ng-if available in all the angular version after 1.1.4

<div ng-if="array.length>0"></div>

if you have any data in array variable then only the div will appear


ui-if was removed at least from latest version angular-ui but since angular 1.1.5 you have ng-if (from this comment)
R
Rizwan

if you want to display "None" when value is "0", you can use as:

<span> {{ $scope.amount === "0" ?  $scope.amount : "None" }} </span>

or true false in angular js

<span> {{ $scope.amount === "0" ?  "False" : "True" }} </span>

T
Tom Stickel

So with Angular 1.5.1 ( had existing app dependency on some other MEAN stack dependencies is why I'm not currently using 1.6.4 )

This works for me like the OP saying {{myVar === "two" ? "it's true" : "it's false"}}

{{vm.StateName === "AA" ? "ALL" : vm.StateName}}

S
Steffomio

Works even in exotic Situations:

<br ng-show="myCondition == true" />

b
btm1

I'll throw mine in the mix:

https://gist.github.com/btm1/6802312

this evaluates the if statement once and adds no watch listener BUT you can add an additional attribute to the element that has the set-if called wait-for="somedata.prop" and it will wait for that data or property to be set before evaluating the if statement once. that additional attribute can be very handy if you're waiting for data from an XHR request.

angular.module('setIf',[]).directive('setIf',function () {
    return {
      transclude: 'element',
      priority: 1000,
      terminal: true,
      restrict: 'A',
      compile: function (element, attr, linker) {
        return function (scope, iterStartElement, attr) {
          if(attr.waitFor) {
            var wait = scope.$watch(attr.waitFor,function(nv,ov){
              if(nv) {
                build();
                wait();
              }
            });
          } else {
            build();
          }

          function build() {
            iterStartElement[0].doNotMove = true;
            var expression = attr.setIf;
            var value = scope.$eval(expression);
            if (value) {
              linker(scope, function (clone) {
                iterStartElement.after(clone);
                clone.removeAttr('set-if');
                clone.removeAttr('wait-for');
              });
            }
          }
        };
      }
    };
  });

G
Gurnard

More recent angular, 6+ I think. You have ng-template with the else conditional hooking up to a tag identifier:

<div *ngIf="myVar else myVarNo">Yes</div>
<ng-template #myVarNo><div>No</div></ng-template>