使用Switch语句循环遍历数组

时间:2015-08-21 11:04:06

标签: javascript angularjs

基本上我有一个显示不同内容的网址列表。一个网址有很多子部分。
而不是制作很多不同的switch语句。我想知道如果可以使用数组。所以,当我点击btn时,我有一个url end / explore /的下拉列表,这总是会改变。

 var exploreAddedLink = ["a", "b", "c", "d", "e" , "f"];

  switch (locationUrl) {
          case '/channels':
              $scope.contentLink = "Edit this Channel";
              $scope.one = "tags";
              $scope.two = "channel";
            break;
          case '/explore/'+exploreAddedLink+'':
              $scope.contentLink = "Title";
              $scope.one = "tags";
              $scope.two = "";
            break;
            case '/all-videos':
                $scope.contentLink = "Edit this Video";
                $scope.one = "videos";
                $scope.two = "";
              break;
          default:

        }

1 个答案:

答案 0 :(得分:0)

我的击球方式将创建一些地图和回调函数,如:

var exploreAddedLink = ["a", "b", "c", "d", "e" , "f"];

var urls = {
  '/channels': function($scope){
    $scope.contentLink = "Edit this Channel";
    $scope.one = "tags";
    $scope.two = "channel";
},
  '/all-videos': function($scope){
    $scope.contentLink = "Edit this Video";
    $scope.one = "videos";
    $scope.two = "";
}};

angular.forEach(exploreAddedLink, function(extraLinkPart){
  urls['/explore/'+extraLinkPart] = exploreAction;
});

function exploreAction ($scope){
  $scope.contentLink = "Title";
  $scope.one = "tags";
  $scope.two = "";
}

/*use*/

urls[locationUrl]($scope);

修改

您可以采取行动以获得正确的行动:

function getUrlAction(url){
   if(url){
     return urls[url];
   }

   return function(){};
}

/*use*/
getUrlAction(locationUrl)($scope);