Javascript缩短和连接功能

时间:2016-07-14 11:42:17

标签: javascript angularjs

我有一个功能,我想缩短并使其更简单,因为我不善于使用javascript我在尝试缩短时会遇到错误:

$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:意外的令牌。

3 个答案:

答案 0 :(得分: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作为属性访问它来调用它。

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

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

在这种情况下,根据布尔值,调用相应的函数并获得返回的承诺,然后解决。

答案 1 :(得分: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');
    });
};

答案 2 :(得分:0)

不太确定代码的逻辑,但是你可以在ArticleService中使用输入参数bulletpointPopular创建一个新方法,这个方法将调用popular()或all(),具体取决于bulletpointPopular值,在这种情况下你的代码会更短,看起来像这样

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