新的角度和打字稿.
我有typcript枚举如下
public enum MyEnum{ A = 0,B = 1,C = 2 }
范围变量as-
$scope.myLetter: MyEnum = MyEnum.B;
枚举检查的正确方法是什么?
选项1:比较html页面中枚举的整数值 –
<div ng-class="{classA: myLetter === 0,classB: myLetter === 1,classC: myLetter === 2}">Test panel</div>
$scope.getClass(value: myLetter): string{ if(value === MyEnum.A) return 'classA'; if(value === MyEnum.B) return 'classB'; if(value === MyEnum.C) return 'classC'; }
并有html元素as-
<div ng-class='getClass(myLetter)'>Test panel</div>
选项3:Angular.js and ng-swith-when – emulating enum的“RyanNerd”回答
对我来说,选项2是可取的,剩余的选项将以ng类的值作为字符串进行检查,这不会给我们静态类型的执行.请分享您的意见或任何其他更好的选择.
Get the class name from the controller scope method
我不喜欢让控制器知道类名的想法.
$scope.myEnumName = (value: MyEnum) => MyEnum[value];
并在模板中使用它:
ng-class="{'A':'ClassA','B':'ClassB','C':'ClassC'}[myEnumName(myLetter)]"
$scope.switchMyEnum = <T>(value: MyEnum,cases: { [value: string]: T }) => cases[MyEnum[value]];
模板:
ng-class="switchMyEnum(myLetter,{'A':'ClassA','C':'ClassC'})
>如果只需要myLetter开关:
$scope.switchMyLetter = <T>(cases: { [value: string]: T }) => cases[MyEnum[$scope.myLetter]];
模板:
ng-class="switchMyLetter({'A':'ClassA','C':'ClassC'})
>如果要在许多范围中使用许多枚举:
angular.module("MyApp",[]) .run(["$rootScope",(root: {}) => { function registerSwitchers(...enumInfos: [string,{ [value: number]: string }][]) { enumInfos.forEach(enumInfo => { var switcherName = enumInfo[0] var enumType = enumInfo[1] root[switcherName] = (value: any,cases: { [value: string]: any }) => cases[enumType[value]]; }); } registerSwitchers( ["switchMyEnum1",MyEnum1],["switchMyEnum2",MyEnum2]); }])