Jea*_*eri 58 angularjs ng-switch
我有以下ngSwitch:
<p ng-switch="status">
<span ng-switch-when="wrong|incorrect">
Wrong
</span>
<span ng-switch-default>
Correct
</span>
</p>
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,我有文本Wrong的两个选项wrong和correct.我试过(你可以看到)使用管道|,但这不起作用.有什么建议 ?
Cha*_*ion 63
对于angular> = v1.5.10,
您可以通过添加ng-switch-when-separator="|"到ng-when节点来完成.
参见文档中的示例.
<span ng-switch-when="wrong|incorrect" ng-switch-when-separator="|">
Run Code Online (Sandbox Code Playgroud)
请参阅此处的讨论https://github.com/angular/angular.js/issues/3410 请注意,根据我的经验,它不适用于数字......但是?
Sal*_*ncı 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>
Run Code Online (Sandbox Code Playgroud)
直播:http://jsfiddle.net/8yf15t2d/
Ed *_*ffe 20
一个人不能有多个条件ng-switch-when.
一种替代方法是使用a ng-if,但在错误处理的情况下,我更喜欢在控制器的范围上填充错误变量,并使用ng-show=error.
pep*_*dip 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;
};
})
Run Code Online (Sandbox Code Playgroud)
那你简直就是
<p ng-switch="status|meaning">
<span ng-switch-when="wrong">
Wrong
</span>
<span ng-switch-default>
Correct
</span>
</p>
Run Code Online (Sandbox Code Playgroud)
虽然在您的情况下,您可能只是想打印一条消息,以便您可以从字典中提取消息...
就像是:
<span ng-if="status">
{{getStatusMessage(status)}}
</span>
Run Code Online (Sandbox Code Playgroud)
使用angular的基本指令无法实现这一点,但如果您愿意,可以编写自己的指令来实现它,并且已经可以与现有的ngSwitch指令进行交互.
ngSwitchController有一个属性cases是地图.每个案例键都带有一个前缀,!默认大小写等于?.每个case值都是一个具有两个属性的对象:transclude和element.
警告:与ngModelController不同,ngSwitchController 不是已发布的API,因此可能会发生变化.
基于最初的ngSwitchWhenDirective,我们可以构建一个多开关,它将与所有现有的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);
});
}
}
});
Run Code Online (Sandbox Code Playgroud)
示例plunker:http://plnkr.co/edit/K9znnnFiVnKAgGccSlrQ?p = preview
| 归档时间: |
|
| 查看次数: |
84260 次 |
| 最近记录: |