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 a Select component in React without relying on the Material-UI library involves customizing a dropdown

Is there a way to achieve a material UI style Select component without using the material UI library in my project? I'm interested in moving the label to the top left corner when the Select is focused. export default function App({...props}) { retu ...

Tips on finding the key associated with a specific value

When a form is submitted, one of the fields being sent is an ID number instead of the name for easier processing by the server. For example: HTML dropdown select <select ng-model="myColor" class="form-control" ng-options = "color.ID as color.color ...

What makes it possible for Vue v3 to handle variables that are undefined?

We are in the process of developing a web application that monitors analytical changes and updates them in real time. While this may not be crucial information, we thought it would be worth mentioning. If you visit Vue.js's official website at https: ...

Namespace remains ambiguous following compilation

I'm currently developing a game engine in TypeScript, but I encountered an issue when compiling it to JavaScript. Surprisingly, the compilation process itself did not throw any errors. The problem arises in my main entry file (main.ts) with these ini ...

Execute and showcase code without redundancies

I have been exploring a way to store JavaScript code within an object and execute specific parts of it upon the user clicking a button. Here's what I've come up with so far: var exampleCode = { test: "$('body').css('background ...

"Looking for a way to automatically close the <li> tag in Vuejs when clicked outside

clickOutside: 0, methods: { outside: function(e) { this.clickOutside += 1 // eslint-disable-next-line console.log('clicked outside!') }, directives: { 'click-outside': { ...

Integrating XML API Requests Using HTML and JavaScript

When there is only one item in the XML document, I want to update my inner HTML with the result of an API call. I have managed to successfully make the API call work when there are multiple items in the XML document (thanks to W3). <!DOCTYPE html> ...

The Vue.js error message "Unable to access property 'array_name' as it is undefined" indicates an issue with

I'm currently working on fetching data using Axios requests and storing it in an array. Below is the code I have been using: props: [ 'products', ], data: function () { return { algolia: '', pro ...

Utilize JavaScript to extract content from a text file and showcase it in a Bootstrap modal pop-up through knockout binding

I'm currently working on a function that reads data from a .txt file (located in the website's root directory) and then displays it in a modal dialog box. I believe I've made progress as the file is recognized during debugging, but unfortuna ...

Tips for simulating or monitoring a function call from a separate file

Within my codebase, there is a function that is triggered upon submission. After the payload has been posted, I aim to execute a function located in a distinct file named showResponseMessage: Contact.js import { onValueChangeHandler, showResponseMessage, ...

What is the best way to ensure that the content container's max-width for a split tier is the same as the width of a full-width tier?

My goal is to create a split tier on a webpage with a 60/40 layout. The size of this tier should be calculated based on the maximum width of the container above it. Using JavaScript and jQuery, I managed to derive the max-width value of the full-width-tier ...

Executing SQL queries in JavaScript using PHP functions

Is it allowed, or is it a good practice? It worked for me, but what issues might I face in the future? Just to clarify, I am new to PHP scripting. // button <button type="button" class="btn btn-primary" id="Submit-button" >Save changes</button> ...

Upgrade from Next.js version 12

Greetings to all! I have recently been assigned the task of migrating a project from next.js version 12 to the latest version. The changes in page routing and app routing are posing some challenges for me as I attempt to migrate the entire website. Is ther ...

The "util" module has been extracted to ensure compatibility with browsers. Trying to use "util.promisify" in client code is not possible

Currently, I'm in the process of scraping LinkedIn profiles with the help of this library: https://www.npmjs.com/package/@n-h-n/linkedin-profile-scraper. Listed below is the code snippet that I am using: <script> import { LinkedInProfileScraper ...

The JavaScript file fails to load when accessing port 8080

As I embark on my journey into backend development, please bear with me. Currently, I am working on a JavaScript program that retrieves text data from my localhost. I have set up an HTTP server using Node.js which serves as a regular HTTP server. The serve ...

The functionality of the document download button using Express.js and node.js appears to be malfunctioning

For my current project, I am aiming to enable users to effortlessly download a document by simply clicking on a designated button. Project Outline: public/client.js console.log('Client-side code running'); const button = document.get ...

An Easy Method for Managing Files in a Node.js Directory: Editing and Deleting Made Simple

Greetings! I am currently in the process of developing a basic blog using express.js. To manage the creation, updating, and deletion of posts based on their unique id, I rely on a data.json file. For each action performed, I utilize fs.writeFile to generat ...

Vue JS encountering Slack API CORS issue while using axios

I am currently developing an application using Capacitor JS & Nuxt JS to interact with the Slack API for setting my Slack status. I have successfully created a Slack App and obtained a xoxp- token, which works perfectly when sending a POST request via Post ...

IntelliJ has removed the connect-flash plugin, preventing me from reinstalling it

Learning node.js is new to me and I encountered a strange issue. While working on implementing login functionality with passportjs, I faced an error where req.flash() was not functioning properly. Oddly enough, it was working fine yesterday when I used it ...

Tips for creating a login page with AngularJS

For my dynamic web application, I am utilizing AngularJS to create a master page structure. In the index.html file, I have an ng-view where I can inject other pages while keeping the menu, header, and footer constant. index.html <body ng-app="mainApp" ...