2016-07-14 71 views
0

我有,我想縮短,並使其更加簡單,因爲我不擅長用JavaScript我不斷收到錯誤,當我試圖縮短這樣的功能:的Javascript縮短和concatinating功能

$scope.doRefresh = function(){ 
    if($scope.bulletpointPopular){ 
     ArticleService.popular().then(function(data){ 
     $scope.articles = data; 
     }) 
     .finally(function() { 
     $scope.$broadcast('scroll.refreshComplete'); 
     }); 
    } 
    else { 
     ArticleService.all().then(function(data){ 
     $scope.articles = data; 
     }) 
     .finally(function() { 
     $scope.$broadcast('scroll.refreshComplete'); 
     }); 
    } 
    }; 

要這樣的:

$scope.doRefresh = function(){ 
     if($scope.bulletpointPopular){ 
      $scope.popular(); 
     } 
     else { 
      $scope.latest(); 
     } 
     .finally(function() { 
      $scope.$broadcast('scroll.refreshComplete'); 
      }); 
     }; 

Erorr:

Uncaught SyntaxError: Unexpected token .

+0

你做了什麼錯誤?你忘了提及 – Ved

回答

1
$scope.doRefresh = function(){ 
    var articleType = $scope.bulletpointPopular? 'popular': 'all'; 

    ArticleService[articleType]().then(function(data){ 
     $scope.articles = data; 
    }).finally(function() { 
     $scope.$broadcast('scroll.refreshComplete'); 
    }); 
}; 

那怎麼樣。所以,我在if和else中的邏輯之間看到的唯一區別是在ArticleService上調用哪個函數。因此,通過從ArticleService作爲屬性訪問它來調用該變量。

OR

$scope.doRefresh = function(){ 
    var articlePromise = $scope.bulletpointPopular? ArticleService.popular(): ArticleService.all(); 

    articlePromise.then(function(data){ 
     $scope.articles = data; 
    }).finally(function() { 
     $scope.$broadcast('scroll.refreshComplete'); 
    }); 
}; 

在這種情況下,基於布爾值,調用相應的函數,並且得到所返回,然後解決的承諾。

0

對代碼的邏輯不太確定,但是您可以在ArticleService中使用輸入參數bulletpointPopular創建一個新方法,並且此方法將根據bulletpointPopular值調用popular()或all(),在這種情況下,您的代碼會更短,看起來像這樣

$scope.doRefresh = function(){ 
    ArticleService.newMethod($scope.bulletpointPopular).then(function(data){ 
     $scope.articles = data; 
     }) 
     .finally(function() { 
     $scope.$broadcast('scroll.refreshComplete'); 
     }); 
}; 
+0

@Chanthu答案似乎更好,不知道可以像那樣調用服務方法 – tratto

1

你可以這樣說:

$scope.popular = function() { 
    return ArticleService.popular(); 
}; 
$scope.latest = function() { 
    return ArticleService.all(); 
}; 
$scope.doRefresh = function() { 
    ($scope.bulletpointPopular ? $scope.popular() : $scope.latest()).then(function(data) { 
     $scope.articles = data; 
    }).finally(function() { 
     $scope.$broadcast('scroll.refreshComplete'); 
    }); 
};