2016-07-14 65 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'); 
    }); 
};