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