AngularJS中: ng-switch-when与OR一起使用

36

ng-switch-when中是否可以使用OR条件?

<div ng-repeat="w in windows" ng-show="visibleWindowId == w.id" ng-switch="w.type">
    <div ng-switch-when="val1 **OR** val2">
        sup
    </div>
</div>
如果不行,那么上述内容该如何实现呢?
谢谢 :)

1
你试过使用 || 吗?val1||val2,我猜应该可以工作。 - mpm
需要一个覆盖,这里是详细的方法:http://stackoverflow.com/questions/17805636/how-can-i-use-ng-switch-to-satisfy-multiple-same-conditions/19146745#19146745 - arkoak
5个回答

19
ngswitch 只允许您比较单个条件。
如果您想测试多个条件,可以使用与 version 1.1.5 可用的 ng-if参考 需要注意的是,使用 ng-ifng-switch从DOM结构中移除元素,而不是显示和隐藏。
当您遍历DOM以查找元素时,这一点非常重要。

正确的答案。但是。。。“当您遍历DOM查找元素时,这很重要。” - 奇怪的是,我认为我从来没有在Angular中这样做过,毕竟,这不是Angular的方式。 - Blowsie
@Blowsie,我也不是很清楚(这难道不是Angular的卖点吗?)。但是有可能会有人创建一个指令并需要那个功能,我宁愿让人们知道并理解他们正在实现什么。 - Malkus
2
当使用CSS选择器如 +, :first-child, :empty 等时,这很相关。 - Tamlyn

16

现在可以使用 ng-switch-when-separator,它在Angular文档中添加于1.5.10版本:

<div ng-repeat="w in windows" ng-show="visibleWindowId == w.id" ng-switch="w.type">
    <div ng-switch-when="val1|val2" ng-switch-when-separator="|">
        sup
    </div>
</div>

8

这也能够正常工作

<div ng-repeat="w in windows" ng-switch="w.type == 'val1' || w.type == 'val2'">
  <div ng-switch-when="true">
    sup
  </div>
</div>


4
这里似乎更适合使用ngIf。 - cdmckay

5
我创建了一个简单的指令来代替ngSwitchWhen,可以允许您为单个标签指定多个情况,同时它还允许您指定动态值而不仅仅是静态值。
但请注意,它只在编译时对表达式进行一次求值,因此您必须立即返回正确的值。对于我的目的来说这是可以接受的,因为我想要使用在应用程序其他地方定义的常量。它可能可以被修改以动态重新评估表达式,但那将需要更多与ngSwitch的测试。
我正在使用angular 1.3.15,但我使用angular 1.4.7进行了快速测试,在那里也工作正常。
代码: Plunker Demo
module.directive('jjSwitchWhen', function() {
    // Exact same definition as ngSwitchWhen except for the link fn
    return {
        // Same as ngSwitchWhen
        priority: 1200,
        transclude: 'element',
        require: '^ngSwitch',
        link: function(scope, element, attrs, ctrl, $transclude) {
            var caseStms = scope.$eval(attrs.jjSwitchWhen);
            caseStms = angular.isArray(caseStms) ? caseStms : [caseStms];

            angular.forEach(caseStms, function(caseStm) {
                caseStm = '!' + caseStm;
                ctrl.cases[caseStm] = ctrl.cases[caseStm] || [];
                ctrl.cases[caseStm].push({ transclude: $transclude, element: element });
            });
        }
    };
});

使用方法

  $scope.types = {
      audio: '.mp3', 
      video: ['.mp4', '.gif'],
      image: ['.jpg', '.png', '.gif'] // Can have multiple matching cases (.gif)
  };

  <div ng-switch="mediaType">
    <div jj-switch-when="types.audio">Audio</div>

    <div jj-switch-when="types.video">Video</div>

    <div jj-switch-when="types.image">Image</div>

    <!-- Even works with ngSwitchWhen -->
    <div ng-switch-when=".docx">Document</div>

    <div ng-switch-default>Invalid Type</div>
  <div>

非常好,我称之为 ng-switch-multiple-when - haki

2

您可以使用ng-class以便在表达式中使用or运算符。此外,Angular-ui还有if指令。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接