修复代码

时间:2015-09-03 02:49:57

标签: ionic

您好我想问一下是否有更好的方法将我的代码转换为更好或更快的方式?如您所见,它是嵌套的if语句。我希望它是一个较小的代码行。有什么帮助吗?

$scope.check = function (viewLocation) {
  if(viewLocation == "videos"){
      $scope.icon_video = 'img/video-active.png';
      $scope.icon_events = 'img/events.png';
      $scope.icon_stocks = 'img/stocks.png';
      $scope.icon_chat = 'img/chat.png';
  }else{
      if(viewLocation == "events"){
         $scope.icon_video = 'img/video.png';
         $scope.icon_events = 'img/events-active.png';
         $scope.icon_stocks = 'img/stocks.png';
         $scope.icon_stocks = 'img/chat.png';
      }else{
        if(viewLocation == "stocks"){
            $scope.icon_stocks = 'img/video.png'
            $scope.icon_stocks = 'img/events.png'
            $scope.icon_stocks = 'img/stocks-active.png'
            $scope.icon_chat = 'img/chat.png'
        }else{
            if(viewLocation == "chat"){
                scope.icon_stocks = 'img/video.png'
                $scope.icon_stocks = 'img/events.png'
                $scope.icon_stocks = 'img/stocks.png'
                $scope.icon_chat = 'img/chat-active.png'
            }else{
                scope.icon_stocks = 'img/video.png'
                $scope.icon_stocks = 'img/events.png'
                $scope.icon_stocks = 'img/stocks.png'
                $scope.icon_chat = 'img/chat.png'
            }
        }
      }

  }
};

2 个答案:

答案 0 :(得分:2)

像这样的可能会工作:

$scope.check = function (viewLocation) {
    $img_arr = array("video","events","stocks","chat");

    foreach($img_arr as $imgcurk => $imgcurv){
        ${"scope.icon_" . $imgcurk} = "img/" . $imgcurk;
        if($imgcurk == viewLocation){
            ${"scope.icon_" . $imgcurk} .= "-active";
        }
        ${"scope.icon_" . $imgcurk} .= ".png";
    }
};

请注意,我没有对此进行过任何测试,但理论适用。

答案 1 :(得分:1)

改善它的一个方法是:

$scope.check = function (viewLocation) {
    $scope.icon_stocks = 'img/video.png'
    $scope.icon_stocks = 'img/events.png'
    $scope.icon_stocks = 'img/stocks.png'
    $scope.icon_chat = 'img/chat.png'

    if (viewLocation == "videos") {
        $scope.icon_chat = 'img/chat-active.png'
    } else if (viewLocation == "events") {
        $scope.icon_stocks = 'img/events-active.png'
    } else if (viewLocation == "stocks") {
        $scope.icon_stocks = 'img/stocks-active.png'
    } else if (viewLocation == "chat") {
        $scope.icon_chat = 'img/chat-active.png'
    }
};

如果有可能至少有一个有效选项卡,那么最后“如果'可以只是一个'否则'