AngularJS:在ng-switch-when中使用多个值

61

我有以下的ngSwitch代码:

<p ng-switch="status">
    <span ng-switch-when="wrong|incorrect">
       Wrong
    </span>
    <span ng-switch-default>
       Correct
    </span>
</p>

如您所见,我对于两个选项 wrongcorrect 都使用了文本 Wrong。我尝试过(如您所见)使用竖线 |,但不起作用。 有任何建议吗?


你能解释一下你的 switch 语句的逻辑吗?你想要做什么? - Alex Choroshin
如果变量status包含值wrongincorrect,我想显示文本wrong。对于所有其他值,它应该显示文本Correct - Jeanluca Scaljeri
7个回答

75

7
尽管文档上写的不是这样,但这项功能尚未包含在v1.5.8中,而将会在1.5.9及以后版本中加入(请参见:https://github.com/flyfly6/angular.js/pull/1)。 - steevee

43

这几乎与使用ng-if相同,但它的优点是您可以在主ng-switch中多次使用ng-switch-when =“true”或default或false。

<p ng-switch on="(status == 'wrong') || (status == 'incorrect')">
    <span ng-switch-when="true">
        Wrong
    </span>
    <span ng-switch-default>
       Correct
    </span>
</p>

直播: http://jsfiddle.net/8yf15t2d/


你的回答应该包含代码的解释以及它如何解决问题的描述。 - AbcAeffchen
11
相比于"ng-if",有什么优点? - Stalinko
1
如果有许多switch case,则会带来性能优势,因为ng-if为每个ng-if设置一个监视器,而ng-switch仅设置一个监视器。如果您在ng-repeat中,则这最相关,因为所有这些监视器都会累加。 - Sámal Rasmussen

20

使用单个ng-switch-when无法同时满足多个条件。

一种替代方式是使用ng-if,但在错误处理的情况下,我更喜欢在控制器中填充一个作用域内的错误变量,并使用 ng-show=error 显示。


16

您可以向 status 添加过滤器,将表示相同含义的值映射为相同的值。

.filter('meaning', function() {
    return function(input) {
      input = input || '';
      if (['wrong', 'amiss','awry', 'bad', 'erroneous', 'false', 'inaccurate',\
           'misguided', 'mistaken', 'unsound', 'incorrect'].indexOf(input) != -1)
          return 'wrong';
      // You can make it generic like this:
      synonymsDictionary = {
        'someWord' : ['syn1', 'syn2', 'syn3' ... ],
        'someOtherWord' : ['otherWordSyn1', 'otherWordSyn2', 'otherWordSyn3' ...]
        .
        .
        .
      };

      for (var word in synonymsDictionary)
          if (synonymsDictionary[word].indexOf(input) != -1)
              return word; // This way you could iterate over a bunch of arrays...

         // Edge case
         else return input;
    };
  })

那么你只需要

<p ng-switch="status|meaning">
    <span ng-switch-when="wrong">
       Wrong
    </span>
    <span ng-switch-default>
       Correct
    </span>
</p>
尽管在你的情况下,你可能只是想打印一条消息,因此你可以从字典中提取消息......

类似于:

<span ng-if="status">
    {{getStatusMessage(status)}}
</span>

2
非常好的但被低估的。 - ErichBSchulz

5

使用angular的基本指令无法实现此功能,但是如果您愿意,可以编写自己的指令来实现此功能,并且已经可以与现有的ngSwitch指令进行接口。

ngSwitchController有一个属性cases,它是一个映射。每个case键都以!为前缀,而默认情况下的case等于?。每个case值都是一个具有两个属性transcludeelement的对象。
警告:与ngModelController不同,ngSwitchController不是发布的API,因此可能会发生更改。

基于原始的ngSwitchWhenDirective,我们可以构建一个multiswitchWhen,它将与所有现有的ngSwitch、ngSwitchWhen和ngSwitchDefault指令一起使用而不会冲突。

.directive('multiswitchWhen', function () {
    return {
        transclude: 'element',
        priority: 800,
        require: '^ngSwitch',
        link: function(scope, element, attrs, ctrl, $transclude) {
            var selectTransclude = { transclude: $transclude, element: element };
            angular.forEach(attrs.multiswitchWhen.split('|'), function(switchWhen) {
                ctrl.cases['!' + switchWhen] = (ctrl.cases['!' + switchWhen] || []);
                ctrl.cases['!' + switchWhen].push(selectTransclude);
            });
        }
    }
});

示例 plunker: http://plnkr.co/edit/K9znnnFiVnKAgGccSlrQ?p=preview

这是一个示例代码,可以在上面进行实验和演示。

优秀的解决方案!应该标记为正确答案。 - Whistler

3
你可以添加另一个 switch case。
例子:
<p ng-switch="status">
    <span ng-switch-when="wrong">
       Wrong
    </span>
<span ng-switch-when="incorrect">
       Wrong
    </span>
    <span ng-switch-default>
       Correct
    </span>
</p>

实际示例:http://jsfiddle.net/choroshin/Zt2qE/2/

6
这是正确的,但并没有回答问题。 - Ed_
那么问题是什么? - Alex Choroshin
2
在ng-switch-when中可以使用多个值,而不仅仅是ng-switch。 - Ed_
但是为什么你想在ng-switch-when中有多个值呢?为什么不能使用另一个ng-switch-when来实现呢?我猜是因为DRY原则吧? - Praym

0

使用ng-switch和选项选择可能会有所帮助

<select ng-model="myVar">
  <option value="option1">Option 1
  <option value="option2">Option 2
  <option value="option3">Option 3
</select>
<div ng-switch="myVar">
  <div ng-switch-when="option1">
     <p>Option 1 is selected .</p>
  </div>
  <div ng-switch-when="option1">
     <p>Option 2 is selected</p>
  </div>
  <div ng-switch-default>
     <p>Option 3 is selected </p>
  </div>
</div>

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