Utilizing an array to pass a series of items to a function parameter

I am currently working on an Angular project that involves a controller and service.

In this setup, the controller sends data and an endpoint to the service.

As of now, the service handles the http request. However, I am in the process of refactoring my code so that the service can match the endpoint from an array list.

This is how the Controller looks:

app.controller('MyController', function($scope, myService) {

    $scope.buttonClick = function(endpoint) {
        myService.postAction(endPoint, $scope.postData)
            .success(function (data, status, headers, config) {

                console.log("success");                   

            })

            .error(function (data, status, headers, config) {

               console.log("error");                    

            });
    }

And here's the MyService code:

app.factory('MyService', function ($http) {

    var endPoints = [
        'cart/cartDetails',
        'customer/addressInfo',
        'payment/ShippingInfo',
    ]

    return {
        postAction: function(endPoint, postData) {
            return $http({
                method: 'POST',
                url: endPoint,
                data: postData,
                headers: {'Content-Type': 'application/json'}
            });
        }
    };
});

When a button is clicked using $scope.buttonClick, one of the endpoints is passed like so:

<button ng-click="buttonClick('ShippingInfo')>Shipping</button>
<button ng-click="buttonClick('addressInfo')>Address</button>
<button ng-click="buttonClick('certDetails')>Cart</button>

Answer №1

Make sure your endPoints are defined as an object

app.factory('MyService', function ($http) {

    var endPoints = {'certDetails': 'cart/cartDetails','addressInfo': 'customer/addressInfo','ShippingInfo': 'payment/ShippingInfo'}


    return {
        postAction: function(endPoint, postData) {
            return $http({
                method: 'POST',
                url: endPoints[endPoint],
                data: postData,
                headers: {'Content-Type': 'application/json'}
            });
        }
    };
});

Answer №2

It is not advisable to proceed with that approach, as the controller would need to know at least the key of the URL endpoint. It would be more efficient to implement the following modification in your factory code:

var endPoints = {'certDetails': 'cart/cartDetails',
                 'addressInfo': 'customer/addressInfo',
                 'shippingInfo': 'payment/ShippingInfo'}


return {
    postCertDetails: post(endPoints['certDetails']),
    postAddressInfo: post(endPoints['addressInfo']),
    postShippingInfo: post(endPoints['shippingInfo'])
};

function post(endpoint){
    return function(postData){
        return $http({
            method: 'POST',
            url: endpoint,
            data: postData,
            headers: {'Content-Type': 'application/json'}
        });
    }
}

Implementation in the controller:

service.postCertDetails({...your data...});

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

Guide on integrating buefy (a vue.js component library) into your Laravel blade template

I'm currently integrating buefy into my project, but I'm encountering issues with using vue.js on Laravel 5.8. Can anyone offer assistance? Here is the code snippet from my app.js: require('./bootstrap'); window.Vue = require('v ...

Tips for refreshing the direction route in google-maps-react

I have an array of coordinates, and when I add a new coordinate to the array, I want the route direction on the map to update accordingly. This is the code snippet from my googlemap.js file: /* global google */ import React, { Component } from "react ...

Why is the abort function in JavaScript important?

What possible scenarios would require me to utilize this feature? ...

Navbar remains visible despite ng-hide directive

I am having issues hiding a navbar based on the user's login status. Despite changing the $scope.loggedIn variable, the navbar does not hide as expected. Why is this happening? View: <nav> <div ng-controller="mainCtrl"> <!-- Lo ...

Clicking the save button in the modal updates the text on both the current tab and any previously clicked tabs

I'm looking to implement tabs that, when clicking on the edit icon, open a modal for editing the content of each tab. The issue I'm currently encountering is that if I open the editor for one tab, close it without saving, then open the editor fo ...

Display or conceal div based on chosen options

I am working on a feature that involves three dropdown select boxes, each containing different sets of demographic attributes. My goal is to show a score based on the combination of selections made by the user. For example, if a user chooses Male, 18-24, A ...

Comparing parameters between two functions in Javascript: a step-by-step guide

I am currently working on solving this problem: var name; var totalScore; var gamesPlayed; var player; var score; // Creating the game player object function makeGamePlayer(name, totalScore, ga ...

Converting Byte strings to Byte arrays in Node.js using JavaScript

Currently facing a challenge while trying to complete the pythonchallenge using JS and Node. Stuck on challenge 8 where I need to decompress a string using bzip2: BZh91AY&SYA\xaf\x82\r\x00\x00\x01\x01\x80\x ...

``When executing the `npm install` command, it does not install the sub-dependencies of a local package

I am facing an issue with my packages. One package named package-a has a dependency on another package called package-b which is not published on npm but resides in my file system. When I try to run npm install from the directory of package-a, the dependen ...

Whenever I attempt to connect to Stripe, my code fails to execute properly

My knowledge of Javascript is limited, but I have a basic understanding. I am currently diving into learning about Stripe and testing it in a local environment with a Wordpress install. Following the Stripe documentation, I have successfully installed Node ...

Identify when a click occurs outside of a text input

Whenever text is typed into the textarea, the window changes color. The goal is to have the color revert back when clicking outside the textarea. <textarea class="chat-input" id="textarea" rows="2" cols="50" ...

When utilizing JavaScript within an Electron application file that is linked with a script tag in an HTML document, there may be limitations on using node modules with

While working on my Electron application, I encountered an issue with referencing a node module using require within an HTML form that includes JavaScript. Specifically, I am having trouble integrating the 'knex' node module into my code. Here i ...

Creating dynamic forms with JQuery and ReactJS

I have been tasked with creating a form-builder that will be integrated into an application. My role is to focus on designing the front-end using ReactJS. The client’s requirements are very similar to the features of the "jQuery Form-Builder," so I decid ...

JavaScript call to enlarge text upon click

I'm struggling to figure out why my font enlargement function isn't working as expected. Below is the code for my font enlargement function: <script type="text/javascript> function growText() { var text = document.getElementBy ...

Load Angular scripts only when needed

I need to develop an application that can dynamically register new Angular Controllers obtained from a script. This application should load the minimum necessary scripts at startup and then fetch additional scripts as needed from other modules. Here' ...

What steps should I take to ensure that the child menus of the v-navigation-drawer component are activated during the initial project launch?

I have created a v-navigation-drawer component with Vue 3 and Vuetify 3. The v-navigation-drawer functions properly, but I want the child menus to be visible by default without requiring the user's click when the project first launches. I am using v- ...

When anchor is set programmatically, the focus outline is not displayed

I am currently facing an issue with my application where I am programmatically setting focus on elements in certain scenarios. While it generally works well, I have noticed that when I set the focus on an anchor element using $("#link1").focus(), the focus ...

Encountering the 401 (Unauthorized) error while attempting to delete data in loopback?

I have a model called companyUsers and when I send a GET request, I am able to retrieve all the data successfully. However, when I try to make a DELETE or PUT request, I encounter a 401 (Unauthorized) error. For example, I made a DELETE request using the ...

Python numpy array not checking for value in tuple

My challenge lies in a function that returns a tuple, and my goal is to determine if a specific element exists within the tuple. Despite not knowing the types of elements present in the tuple, I am certain that I require an exact match. To illustrate: 1 in ...

Exploring the functionality of the onblur HTML attribute in conjunction with JavaScript's ability to trigger a

How do the HTML attribute onblur and jQuery event .trigger("blur") interact? Will both events be executed, with JavaScript this.trigger("blur") triggering first before the HTML attribute onblur, or will only one event fire? I am using ...