AngularJS - 指令中的动态切换案例

时间:2016-09-20 07:44:29

标签: javascript angularjs switch-statement

指令

myApp.directive("progressingIndex", function ($compile, $rootScope, constant) {


     var linker = function (scope, element, attrs) {
     var Id = $rootScope.Obj.pictureId;

switch (Id) {
        case constant.picturebox00: $rootScope.Obj.progressing00 = true; break;
        case constant.picturebox01: $rootScope.Obj.progressing01 = true; break;
        case constant.picturebox02: $rootScope.Obj.progressing02 = true; break;
        case constant.picturebox03: $rootScope.Obj.progressing03 = true; break;
        case constant.picturebox10: $rootScope.Obj.progressing10 = true; break;
        case constant.picturebox11: $rootScope.Obj.progressing11 = true; break;
        case constant.picturebox12: $rootScope.Obj.progressing12 = true; break;
        case constant.picturebox13: $rootScope.Obj.progressing13 = true; break;
        case constant.picturebox20: $rootScope.Obj.progressing20 = true; break;
        case constant.picturebox21: $rootScope.Obj.progressing21 = true; break;
        case constant.picturebox22: $rootScope.Obj.progressing22 = true; break;
        case constant.picturebox23: $rootScope.Obj.progressing23 = true; break;
        case constant.picturebox30: $rootScope.Obj.progressing30 = true; break;
        case constant.picturebox31: $rootScope.Obj.progressing31 = true; break;
        case constant.picturebox32: $rootScope.Obj.progressing32 = true; break;
        case constant.picturebox33: $rootScope.Obj.progressing33 = true; break;
}

    $compile(element.contents())(scope);  
    };
    return {
        restrict: "E",
        link: linker
    };
});

此处var Id为我提供了0001等的价值。如何通过附加Id动态生成switch语句的案例?

1 个答案:

答案 0 :(得分:1)

switch(constant['picturebox'+Id]) {
    case constant['picturebox'+Id]: $rootScope.Obj['progressing'+Id] = true; break;
}

这足以测试所有案例。