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

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

但在angular中,我似乎仅限于显示和隐藏html标签中包装的东西

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

在angular中,推荐使用什么方式有条件地显示和隐藏内联内容,只使用{{}}而不是将内容包装在html标签中?


当前回答

如果我没理解错的话,我想你有两种方法。

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

下面以一个简单的滤镜为例。

<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+。你有一个带有else条件的ng-template连接到一个标签标识符:

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

当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

Angular UI库有内置的指令UI -if,用于模板/视图中的条件,直到Angular UI 1.1.4

例子: 在Angular UI中支持到UI 1.1.4

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

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

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

如果你在数组变量中有任何数据,那么只有div会出现

我把我的也加入其中:

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

在Angular 1.5.1中也是如此(因为应用程序依赖于其他MEAN堆栈依赖,所以我目前没有使用1.6.4)

这为我工作像OP说{{myVar === "二" ?"这是真的":"这是假的"}}

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