Reputation: 1811
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 .
Upvotes: 0
Views: 31
Reputation: 10460
You can do it like this:
$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');
});
};
Upvotes: 1
Reputation: 252
not quite sure about the logic of you code, but you can make a new method in ArticleService with an input parameter bulletpointPopular and this method will call either popular() or all() depending on bulletpointPopular value and in this case your code will be shorter and look like this
$scope.doRefresh = function (){
ArticleService.newMethod($scope.bulletpointPopular).then(function(data){
$scope.articles = data;
})
.finally(function() {
$scope.$broadcast('scroll.refreshComplete');
});
};
Upvotes: 0
Reputation: 1794
$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.
Upvotes: 1