Functions for abbreviating and combining strings in Javascript

Looking for help to simplify and shorten a Javascript function:

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

Simplified version attempted:

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

Error message received:

Uncaught SyntaxError: Unexpected token .

Answer №1

$scope.refreshArticles = function (){
    var type = $scope.bulletpointPopular? 'popular': 'all';

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

Interesting approach. The key difference lies in the conditional statement determining which function to call on ArticleService. It's a smart move to store this decision as a variable and access it dynamically from ArticleService.

Alternatively

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

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

In this scenario, depending on the boolean value, the corresponding function is invoked to get the promise returned for resolution.

Answer №2

Here is a way to achieve this:

$scope.popularPosts = function() {
    return PostService.getPopularPosts();
};
$scope.latestPosts = function() {
    return PostService.getAllPosts();
};
$scope.refreshPosts = function() {
    ($scope.showPopular ? $scope.popularPosts() : $scope.latestPosts()).then(function(data) {
        $scope.posts = data;
    }).finally(function() {
        $scope.$broadcast('scroll.refreshComplete');
    });
};

Answer №3

I'm not totally clear on the reasoning behind your code, but one way to simplify it could be by creating a new method in ArticleService that takes an input parameter called bulletpointPopular. This new method would then decide whether to call the popular() or all() function based on the value of bulletpointPopular. Implementing this change would make your code shorter and cleaner.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating dynamic visual elements on a webpage using HTML: Video

As I continue to learn HTML, CSS, and JavaScript to create a basic website for educational purposes, I have successfully embedded a video stored in my drive using the video element on an HTML page. However, I now aim to also display the video's title, ...

Tips for ensuring a custom menu closes when clicking outside of it instead of on the menu itself

Building off a recent inquiry, I am aiming to have my menu close whenever I click outside of it. At the moment, clicking the "Hamburger Menu Button" opens and closes the menu. It will also close when I click a link on the menu or the menu itself. However, ...

Is there a way to achieve a XNOR-like response with necessary input?

I'm currently working with a form that looks like this: <form> <input type="text" name="input1"> <input type="text" name="input2"> <button type="submit"> ...

"Failure to manipulate the style of an HTML element using Vue's

<vs-tr :key="i" v-for="(daydatasT, i) in daydatas"> <vs-td>{{ daydatasT.Machinecd }}</vs-td> <vs-td>{{ daydatasT.Checkdt }}</vs-td> <vs-td>{{ daydatasT.CheckItemnm }}< ...

What could be causing the failure of the update for this computed property in my Vue 3 application?

Currently, I am in the process of creating an audio player using Vue 3 and the Napster API. About the Project I have managed to make the vinyl rotate by utilizing a CSS keyframes-based animation paired with the computed property isSpinning. I intend for ...

How can we effectively implement conditional rendering when dealing with components that are nearly identical?

Depending on whether the user is a professor, student, or not logged in, I render different landing pages. The landing pages are quite similar, with the only distinction being the buttons displayed. While I could easily achieve this using inline conditions ...

An animation triggered by scrolling using the @keyframes rule

Is it possible to smoothly animate a variable font using @keyframes on scroll and have it complete the animation loop when the user stops scrolling, rather than snapping back to the starting position? I've managed to make the animation work, but it l ...

Creating adaptable HTML images by specifying width and height attributes within the image tag

My current website setup involves loading a full image and automatically adjusting its size to fit the screen by setting the image width to 100% in CSS. While this method works smoothly, it may not be following standards as I am not specifying width and he ...

What strategies can I implement to integrate Cordova with a combination of Meteor and React?

I'm currently struggling to implement a Cordova plugin with Meteor and React. According to the documentation: You should wrap any functionality that relies on a Cordova plugin inside a Meteor.startup() block to ensure that the plugin has been fully ...

Examining AngularJS Jasmine Promises in IsolationDive into the world

Seeking help for testing a mocked Service with chained promises. Factory for Testing app.factory('factory', [ 'service', function( service ){ var baz; return { updateMe: function( updateObj ){ // do stuff with upd ...

Error alert: TypeScript typings issue - Naming conflict with Promise / Failure to locate name Promise

I am currently working on a client/server JavaScript application and I am facing a significant issue with Promises. It appears that they are either undefined or duplicated, and this problem seems to be related to the @types package. npm install --save @ty ...

I'm looking to create a unit test for my AngularJS application

I am currently working on a weather application that utilizes the to retrieve weather data. The JavaScript code I have written for this app is shown below: angular.module('ourAppApp') .controller('MainCtrl', function($scope,apiFac) { ...

Retrieving Hyperlinks from JavaScript Object for Integration with D3-Created Table

Issue: I'm facing a problem where the HTML link extracted from an Associative Array is treated as a string instead of being applied as a clickable link in the browser. For a detailed visual example and code snippet, visit: http://example.com/code Da ...

Tips for changing the click event of a button with .on/off

My approach for attaching and detaching event handlers is through on()/off(). HTML: <div id='load' class="UnfiledContainer"> <button onclick="loaded()">Try it</button> <p id="demo"></p> </div> JS: ...

Getting image blob data with Cropper Js in a Laravel controllerNeed help on how to get image blob data

I've been working with Cropper.js and Laravel. I managed to crop an image, put it into FormData, and send it to the Laravel controller using jQuery Ajax. However, I encountered a problem where I am not receiving any data in the controller, only an err ...

Discover a non-null string within a deeply nested data structure

Within the 'task' object, the value of the 'door' property can vary each time it is accessed: var task = {}; task["123"] = [{"door":""}, {"door":""}, {"door":""}, {"door":""}]; task["456"] = [{"door":""}, {"door":"close"}, {"door":"" ...

Creating a new version of an existing method found within a component in a Vue store.js file

As I navigate through the learning curve of vue.js, a seemingly simple question has arisen: how can I achieve the following task? Within one of my vue components, I am facing challenges with the implementation of the "loadSuggestedUsers" method. Here is t ...

Efficient - Managing numerous database connections

I am currently working on a project using node.js and I have created a login form where users need to select the database they want to connect to. However, I am uncertain about how to establish a connection with the selected database. Is there a way for m ...

Populating a Listview in jqueryMobile with dynamic elements

I am struggling with my listview. Whenever I try to add or remove items from the list, the jquery mobile styling does not get applied to the new content that is added. <ul data-role="listview" id="contributionList"> <li id="l1"><a>5. ...

Exploring Angular 9: Harnessing the Power of Fork Join with an Array of

I have a challenge where I need to send multiple API requests to an endpoint by iterating over an array of values To handle this, I decided to use rxjs library and specifically the forkJoin method //array to keep observables propOb: Observable<any>[ ...