我创建了一个简单的指令来代替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>