Marco Marco - 4 months ago 20
AngularJS Question

Javascript shortening and concatinating functions

I have a function that I would like to shorten and make it more simple, since I am not good with javascript I keep getting errors when I try to shorten this:

$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');
});
}
};


To this:

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


Erorr:


Uncaught SyntaxError: Unexpected token .

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

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

How about that. So, the only difference I see between the logic in if and else if which function to call on ArticleService. So, make that a variable and invoke it by accessing it from ArticleService as a property.

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');
    });
};

In this case, based on the value of the boolean, invoke the appropriate function and get the promise that's returned and then resolve.