Repeated use of AngularJS' $http.get method on the same form

I am working on developing an application that involves a form where users can input products. Using an AngularJS service called RateInfoService, I retrieve the price information and inject it into the DOM. For example, if the user types in "Milk," the displayed rate will be {{rate}} -> $2.

If the user then fills in "Chips," the rate will adjust accordingly to {{rate}} -> $1.50.

However, my goal is to allow users to input multiple products consecutively and see them all listed on the page. So, ideally, after typing in Milk followed by Chips, the display should show: Milk->$2 & Chips->$1.50.

To achieve this functionality, I am considering using an array to store the entered products for further processing. One challenge I anticipate is managing the refresh rate while updating the data seamlessly.

.controller("MainCtrl", function($scope, $http, $timeout, $ionicPlatform, $cordovaLocalNotification, $ionicPopup, RateInfoService, AlarmService, MonitorService) {
      $scope.refreshRate = 5000;

      $scope.refreshData = function() { 
        RateInfoService.getMarket($scope.alarmingMarket).success(function(data) {
          $scope.rate = data.query.results.rate.Rate;
          $scope.updateTime = data.query.results.rate.Time;
        })
  }



<label class="item item-input">
 <span class="input-label">Product name</span>
 <input type="text" min="3" ng-model="hard" name="text" autofocus required>
</label>

Additionally, when a user submits a product, the following function is triggered:

  $scope.submit = function() { 
  $scope.alarmingMarket = $scope.hard
  console.log($scope.monitors);
};

The line "$scope.alarmingMarket = $scope.hard" ensures that market data is fetched only after the form submission.

For retrieving the price data, I rely on the RateInfoService: http://pastebin.com/gHfhzMjR

Recently discovered the possibility of including multiple objects in the URL link:

https://query.private%20in%20("Milk","Chips")&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=

My main query revolves around implementing this feature efficiently within AngularJS as I am relatively new to this framework (3 weeks).

This section illustrates the JSON formatted view - explaining the line "$scope.rate = data.query.results.rate.Rate;"

  "results": {
   "rate": [
    {
     "id": "MILK",
     "Name": "MILK",
     "Rate": "1.1054",
     "Date": "10/26/2015",
     "Time": "9:37pm",
     "Ask": "1.1056",
     "Bid": "1.1052"
    },
    {
     "id": "CHIPS",
     "Name": "CHIPS",
     "Rate": "1.5349",
     "Date": "10/26/2015",
     "Time": "9:37pm",
     "Ask": "1.5352",
     "Bid": "1.5346"

I trust this provides adequate insight. *** Apologies for any formatting issues experienced. Despite a clear preview on stack overflow, certain elements may not render correctly upon publishing. Some code sections might lack proper highlighting.

Answer №1

Here is my solution:

    $scope.alarmingMarket = [];
  $scope.submit = function() { 

     // $scope.alarmingMarket = $scope.hard
     $scope.alarmingMarket.push($scope.hard);
      console.log($scope.alarmingMarket);
    };

This piece of code is used to add all elements to the $scope.alarmingMarket array.

We also have a service that retrieves market rates:

    module.service('RateInfoService', function($http) {
        return {
                getMarket: function(alarmingMarket) {
                    var market = alarmingMarket
                        return $http.get('https://query.private%20in%20(%22'+ market  + '%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=')
                }
        }
})

In this context, 'market' refers to the array of markets.

Furthermore, there is a function to parse JSON data:

 $scope.refreshData = function() { 
RateInfoService.getMarket($scope.alarmingMarket).success(function(data) {
  if($scope.alarmingMarket.length <= 1){ //if alarmingMarket[] has only 1 market
    $scope.rate = [];
    $scope.rate.marketid = data.query.results.rate.id;
    $scope.rate.rate = data.query.results.rate.Rate;
    $scope.rate.updateTime = data.query.results.rate.Time;
    console.log($scope.rate);
  }else{
  angular.forEach(data.query.results.rate, function (value, key) {
    $scope.rate = [];
    $scope.rate.marketid = data.query.results.rate[key].id;
    $scope.rate.rate = data.query.results.rate[key].Rate;
    $scope.rate.updateTime = data.query.results.rate[key].Time;
    console.log($scope.rate);
});
  }
})

Answer №2

Apologies for the inconvenience, my reputation is not high enough to leave a comment at this time. If you found this response helpful, please consider giving it a thumbs up so that I can increase my reputation.

Based on your description, it appears that you are attempting to iterate over items selected by the user and retrieve the latest rate for each item. It's unclear whether $scope.alarmingMarket is an array of items or something else.

If your goal is to fetch the most recent rates for the user-selected items, you will need to pass the entire array of items and receive back another array. Then, let ng-repeat handle the rest by assigning the values to $scope.alarmingMarket (assuming that is your list of items).

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

Loading data dynamically in the Highcharts ng library allows for real-time updates to the

I'm currently working on integrating highcharts ng into my Angular project, but I'm encountering issues with data not populating. It seems like there might be a problem related to the loading of the DOM and the function call. Here's my HTML ...

Having trouble implementing a login theme for keycloak using vue and vuetify

My goal is to set up a login page for keycloak using vue and vuetify. After trying various guides and projects, I haven't been able to achieve success. While I managed to display some logs, the app itself didn't render. To simplify, I intended ...

When trying to revert back to the original content after using AJAX to display new HTML data, the .html() function

Here is the JavaScript I am using to handle an ajax request: $(document).ready(function() { // Variable to hold original content var original_content_qty = ''; $('.product-qty-<?php echo $products->fields[' products_id ...

What could be causing my XML file to fail to load on Websphere Virtual Server?

I'm currently working on dynamically generating a navigation menu by parsing an XML file using jQuery within a Dynamic Web Project in IRAD (eclipse). Here is the structure of the XML: <?xml version="1.0" encoding="utf-8" ?> <MenuRoot> ...

What is the best way to initiate a re-render after updating state within useEffect()?

I'm currently strategizing the structure of my code using React hooks in the following manner: Implementing a state variable to indicate whether my app is loading results or not The loading state turns to true when useEffect() executes to retrieve da ...

Steps for transforming a JSON into a Class to generate objects

My JSON data is displayed below: var nodeclienthash={ socket:null, init : function() { // Initializing socket.io this.socket = new io.Socket(this.config.host, {port: this.config.port, rememberTransport: false}); } }; I am currently looking t ...

Steps for adding an image to Firebase

I recently started a project using React and Firebase. After going through some tutorials, I managed to add and read text from Firebase successfully. Now I am working on displaying data like name, estate, and description in a modal on my React Firebase. M ...

Discovering an <a> element with an href attribute containing two specified strings

Here's what I have: $("a[href*='string1' && 'string2']") Unfortunately, this code didn't work for me. I also attempted: $("a:contains('string1' && 'string2')") The second one only return ...

Can you please advise me on where I should send this request?

Whenever I click the button, my intention is to trigger a function that will transfer data to the template and open it up. Here's the code for the button click function: function openForm () { const amount = select.value; $ .ajax ({ ...

Arranging a numerical array using a function

As someone who is brand new to coding and still getting the hang of Javascript, I've been taking some basic courses and trying out challenges on my own. Despite searching for an answer to my question, I haven't found anything quite like it. If an ...

Is it possible to transfer a variable to a modal window by clicking on a link?

Here is a link with sample data value "data-id" that I want to pass: <a href="#edit_task" data-toggle="modal" data-id="WAH"><i class="fas fa-edit fa-lg fa-fw"></i></a> Javascript code to open the modal and assign the data value to ...

"Seeking assistance with character encoding and optimizing code - can anybody help me

Hello everyone, I am new to Stack Overflow and I have encountered a problem that I hope you can help me with. Due to a recent arm injury, I need to find a quicker way to copy and paste email templates into an email editor in Siebel. However, I am strugglin ...

How can I reset the search input in v-autocomplete (multiple) after selecting a checkbox from the drop-down menu?

I am facing an issue with the v-autocomplete component from Vuetify. Currently, when I enter "Cali" in the search input and select "California" from the dropdown list, the "Cali" value remains in the search input field. I need the entered value to be clear ...

JavaScript quiz featuring randomized questions with selectable radio buttons

I need assistance in creating a feature on my webpage where users can select the number of questions they want to answer (ranging from 1 to 10). The selected number of questions should then be displayed randomly, without any duplicates. I am not very famil ...

Error message: Unable to access the state property of an undefined object

I've been attempting to integrate a react sticky header into my stepper component. However, I've encountered an issue where it doesn't render when added inside my App.js file. As a result, I've started debugging the code within App.js ...

Encountering a 400 (Bad Request) error while making a POST request to the server in a MERN

In my reactjs application, I added a button to delete user accounts. When the button is clicked, a form appears where users need to enter their password and click on Delete to confirm. However, when testing this feature, clicking on the Delete button does ...

How can I retrieve text adjacent to a checked input checkbox by using JQuery (or JavaScript)?

Here is the HTML block under consideration: <div class"radioGroup"> <input type="radio" value="0"> This option is NOT selected <input type="radio" value="1" checked = "checked" > This option is selected <inpu ...

Iterate over a collection of JSON objects and dynamically populate a table with statistical data

In JavaScript, I am trying to dynamically generate a table with statistical data from an API that contains an array of JSON objects. The JSON data has a property called "score" which is interpreted as follows: score: 5 (excellent); score: 4 (very good); ...

Seeking a way to keep the returned Ajax string consistent and prevent it from fading away after page transition

I have a form that appears when the user clicks on the "Edit" link, allowing them to input their profile information. Upon submission, the data is processed via Ajax and saved in an SQL database using a PHP script. After saving the new profile, I would lik ...

Exploring the functionality of closing a modal in Karma-Jasmine testing

THE ISSUE AT HAND: In my Angular / Ionic app, I am currently in the process of testing a modal to ensure it is functioning correctly. While I have successfully tested that the modal opens as expected, I am facing difficulties in testing the proper closin ...