angular.js中的内联条件

时间:2013-01-04 20:22:48

标签: angularjs if-statement ternary-operator

我想知道是否有一种方法可以有条件地显示内容而不是使用ng-show等。例如在backbone.js中,我可以在模板中使用内联内容做一些事情,如:

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

但在角度方面,我似乎仅限于显示和隐藏包含在html标签中的内容

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

使用{{}}而不是将内容包装在html标记中,有条件地以角度显示和隐藏内嵌内容的角度是什么?

11 个答案:

答案 0 :(得分:707)

Angular 1.1.5增加了对三元运营商的支持:

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

答案 1 :(得分:131)

编辑:2Toad's answer below正是您要找的! Upvote那件事

如果您使用的是Angular&lt; = 1.1.4,则此答案将执行:

还有一个答案。我发布了一个单独的答案,因为它更像是对某个解决方案的“精确”尝试,而不是一系列可能的解决方案:

这是一个过滤器,它将执行“立即if”(aka iif):

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

可以像这样使用:

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

答案 2 :(得分:60)

成千上万的方法来抚养这只猫。我意识到你要特别在{{}}之间询问,但对于其他来到这里的人,我认为值得展示一些其他选择。

在$ scope 上运行(IMO,这是大多数情况下最好的选择):

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

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

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

ng-show和ng-hide当然:

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

Bertrand建议的自定义过滤器。 (如果你不得不一遍又一遍地做同样的事情,这是你最好的选择)

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

{{foo | myFilter}}

或自定义指令:

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>

就个人而言,在大多数情况下,我会在我的示波器上使用一个函数,它使标记非常干净,并且它的实现快速而简单。除非,也就是说,你要一遍又一遍地做同样的事情,在这种情况下,我会考虑Bertrand的建议,并根据具体情况创建一个过滤器或可能的指令。

与往常一样,最重要的是您的解决方案易于维护,并且希望可以测试。这完全取决于您的具体情况。

答案 3 :(得分:18)

我正在使用以下条件在无法使用ng-class时有条件地设置类attr(例如在设置SVG样式时):

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

同样的方法应该适用于其他属性类型。

(我认为你需要使用最新的不稳定Angular来使用ng-attr-,我目前正在使用1.1.4)

我发表了一篇关于使用AngularJS + SVG的文章,讨论了这个问题和相关问题。 http://www.codeproject.com/Articles/709340/Implementing-a-Flowchart-with-SVG-and-AngularJS

答案 4 :(得分:15)

要检查变量内容并使用默认文本,您可以使用:

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

答案 5 :(得分:3)

如果我理解你,我认为你有两种方法可以做到。

首先,您可以尝试ngSwitch,第二种方法是创建自己的filter。可能ngSwitch是正确的方法,但是如果你想隐藏或显示内联内容只需使用{{}}过滤器即可。

这是一个fiddle,以简单的过滤器为例。

<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';
}

答案 6 :(得分:3)

Angular UI库具有内置指令ui-if for condition in template / Views upto angular ui 1.1.4

实施例: 在Angular UI中支持ui 1.1.4

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

ng-如果在1.1.4之后的所有角度版本中都可用

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

如果数组变量中有任何数据,则只显示div

答案 7 :(得分:2)

使用Angular 1.5.1 (现有应用程序依赖于其他一些MEAN堆栈依赖项,这就是我目前没有使用1.6.4的原因)

这对我来说就像OP说{{myVar === "two" ? "it's true" : "it's false"}}

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

答案 8 :(得分:2)

如果要在值为“0”时显示“无”,则可以使用:

<span> {{ $scope.amount === "0" ?  $scope.amount : "None" }} </span>
角度js中的

或true false

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

答案 9 :(得分:1)

即使在异国情调中也能工作:

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

答案 10 :(得分:0)

我会把我扔进混合物中:

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

这会对if语句进行一次计算并且不添加监听监听器但是你可以为具有set-if的元素添加一个额外的属性 - 如果名为wait-for =“somedata.prop”,它将等待该数据或属性在评估if语句之前设置一次。如果您正在等待来自XHR请求的数据,那么附加属性可以非常方便。

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');
              });
            }
          }
        };
      }
    };
  });