Tips for creating dynamic $http.get URLs in AngularJS

Is it possible to create a dynamic URL where the selected value from the first drop-down menu automatically gets added to the end of the URL like this: .

For example, if we select USD in the first drop-down menu, the URL will become , and the JSON data will be retrieved from that updated URL.

Answer №1

When using ngModel on the first select, it will store the selected value. To incorporate this into the URL, fetch the data from $scope.fromType and append it like so:

$http.get('http://api.fixer.io/latest?base=' + $scope.fromType.label).then(function(res) {
    $scope.fromValue = 1;
    $scope.ConvertCurrency();
    var i = 0;
    angular.forEach(res.data.rates, function(value, key) {
        if (key == "USD" || key == "EUR" || key == "CAD") {
            $scope.rates.push({ value: value, label: key });
        }
        i++;
    });
});

Update

I assumed a few things here.

  1. Initially, load all rates in the first select ($scope.getAllRates())
  2. When a rate is selected in the first select, load rates associated with that currency in the other select ($scope.getRate())

If this applies to your scenario, your view should look like this

<div ng-app="CurrencyConv" ng-controller="ConvertCtrl">
    <input type="number" placeholder="0.00" ng-model="fromValue" ng-change="ConvertCurrency();" min='0'>
    <select ng-model="fromType" required ng-change="ConvertCurrency(); getRate();" ng-options="f as f.label for f in rates"></select> 

    <input type="text" placeholder="0.00" ng-model="toValue" ng-change="ConvertCurrency()">
    <select ng-model="toType" required ng-change="ConvertCurrency()" ng-options="f as f.label for f in toRates"></select>
</div>

And the controller

App.controller('ConvertCtrl', ['$scope', '$http', function($scope, $http) {
    $scope.rates = [];
    $scope.toRates = [];

    $scope.toType = {};
    $scope.fromType = {};
    $scope.fromValue = 1;

    $scope.getAllRates = function(){
        $http.get('https://api.fixer.io/latest').then(function(res) {
                angular.forEach(res.data.rates, function(value, key) {
                    if (key == "USD" || key == "EUR" || key == "CAD") {
                        $scope.rates.push({ value: value, label: key });
                    }
                });
            });
    };

    $scope.getRate = function(){
       $scope.toRates = [];
       if(typeof $scope.fromType.label !== undefined){
        $http.get('https://api.fixer.io/latest?base=' + $scope.fromType.label).then(function(res) {
                $scope.fromValue = 1;
                $scope.toValue = 0;
                angular.forEach(res.data.rates, function(value, key) {
                    if (key == "USD" || key == "EUR" || key == "CAD") {
                        $scope.toRates.push({ value: value, label: key });
                    }
                });
                $scope.toType = $scope.toRates[0];
                $scope.ConvertCurrency();
            });
       }
    };

    $scope.ConvertCurrency = function() {
        if($scope.toRates.length > 0){
          $scope.toValue = $scope.fromValue * ($scope.toType.value * (1 / $scope.fromType.value));
        }
    };

    //init
    $scope.getAllRates();
}]);

Feel free to check out the plunker

Answer №2

Assign ng-model to the select element and save the selected value in $scope variable. When sending a request, use this value as a parameter.

    $http.get('http://api.fixer.io/latest', { params:{base: $scope.fromType.label}}).then(function(res) {
    });

Answer №3

To include your ngModel in the request URL, simply append it.

$scope.sendRequest = function(offset){

   $http.get('http://api.fixer.io/latest?base='+$scope.fromType.label).then(function(res) {
    $scope.fromValue = 1;
    $scope.ConvertCurrency();
    var i = 0;
    angular.forEach(res.data.rates, function(value, key) {
        if (key == "USD" || key == "EUR" || key == "CAD") {
            $scope .rates.push({ value: value, label: key });
        }
        i++;
    });
   });
 }

  $scope.ConvertCurrency = function() {


    $scope.toValue = $scope.fromValue * ($scope.toType.value * (1 / $scope.fromType.value));
 $scope.sendRequest();
};

If you require making different requests each time, create a function for your request and invoke it.

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

What's the Purpose of Using an Arrow Function Instead of Directly Returning a Value in a React Event Handler?

After skimming through various textbooks and blog posts, I've noticed that many explanations on event handlers in React are quite vague... For example, when instructed to write, onChange = {() => setValue(someValue)} onChange = {() => this.pro ...

What is the method to deactivate multiple links using jQuery?

Below is the HTML code: <a title="Login" data-href="/MyAccount/Access/Login" data-title="Admin" data-entity="n/a" id="loginLink" class="nav-button dialogLink"><b>Login</b></a> <a title="Register" data-href="/MyAccou ...

Void operation modifies the contents of an array

My code is behaving strangely and I can't seem to figure out why. It's mysteriously changing the list without any explicit instructions to do so, and it's also affecting every duplicate item in the list instead of just one. Let me try to exp ...

Iterate over each option in a select dropdown menu and modify them

Below is the test code snippet I am working with: ID = { CreatedBy: { id: 'createdBy' }, ModifiedBy: { id: 'modifiedBy' } } Profile = { All: { text: 'All', val: 0 }, Sys: { text: '<a href="/cdn-cgi/l/emai ...

Ways to identify which arrays within an object contain an element

This question is unique as it pertains to objects of arrays rather than arrays of objects. I am working with a data structure like the one below and my goal is to determine if any of the arrays inside the object have values. What I'm looking for is a ...

One method for checking the connectivity status of an IE7-based web browser

I am developing an app that uses an embedded IE 7 browser and I need to verify if the user has an active internet connection using a static HTML page with JavaScript. Although Offline.js is a great library, it won't work in this scenario as JavaScrip ...

A detailed guide on sending Joomla form information to a controller function using Ajax communication

Within my Joomla 3.3 form, I have integrated an ajax script aimed at dynamically updating some form fields. The core of the script looks like this: formdata = new FormData(); jQuery.ajax({ type: "POST", dataType: "json", timeout: 6000, url: "index.php?opt ...

What is the best way to access a key from an object within the map function?

What is the method to extract the key from an object in ReactJS? {this.state.data.map((object, index) => ( <div>{Object.keys(object)}</div> ))} For example, if this.state.data contains: [{mykey1:23},{mykey2:24},{mykey3:34}] T ...

Automated tools and frameworks for the testing of website performance

Hello, I have a website that heavily relies on AJAX for server communication. I am looking to conduct performance and stress testing using automated scripts. Can you provide any suggestions or recommendations? I am specifically interested in the functiona ...

Validate whether a value in a JSON object on iOS is either false or a string

I am trying to determine if my value includes the string "false" or another type of string. Here is the JSON data I am working with: {"success":true,"name":[{"image":false},{"image":"https:\/\/www.url.com\/image.png"}]} This is the portio ...

What is the best way to implement a subquery using EXISTS in Knex?

I'm currently facing challenges while constructing a query using knex, specifically when it comes to incorporating the 'WHERE' clause with the condition EXISTS (SELECT * FROM caregiver_patient WHERE patient_id IN (0,1)). Below is the origin ...

How to use jQuery to remove the last element from an array when the back button

Currently encountering an issue with removing the last element from an array when a back button is clicked. The console is displaying the correct elements in the array, but it seems that the array.slice function is not working as expected, and I'm str ...

Jquery assigns the value of the last output to a variable

When it comes to sending comments to a database, I have encountered an issue with my code involving jQuery and AJAX. <script type="text/javascript"> $(document).ready(function() { $('#comm1').keypress(function(event) { ...

Retrieving JSON parameters using $http.get in Angular from one URL and then from another source

As a newcomer to Angular, I am working on setting up basic UI components. I have successfully set up a RESTful Spring service and tested it using curl like this: curl http://myPersonalSite.com:1313/service/event?id=1 This command returns a JSON response ...

md-auto-complete problem with search query

Hi there, I am currently facing an issue with my md auto complete search box. The problem arises when I type a name and the search function is triggered. This search function calls an API, but in the meantime, it returns a null array to the auto complete f ...

Having difficulty validating the field accurately with Angular.js

In order to validate the input field in accordance with the user's needs using AngularJS, I have shared my code below: <div ng-class="{ 'myError': billdata.longitude.$touched && billdata.longitude.$invalid }"> <input type ...

Understanding AMBARI and Demonstrating How to Set Values in JSON Using REST API

Here is an API example that will stop the Kafka service in Ambari. export service=kafka curl -u admin:admin -i -H 'X-Requested-By: ambari' -X PUT -d '{"RequestInfo":{"context":"_PARSE_.STOP.$service","operation_level":{"level":"SERVICE","c ...

What is causing the backslash character to be removed from my ajax request?

When using Ajax to call a rest endpoint, the request takes two parameters: user and permission. $.ajax({ type: 'GET', cache: false, url: "/app/Rest/4.0/UserManagement/AddPermissionToUser", data: { username: encodeURI(user ...

unable to interpret standard object class

I have been trying to access elements from a std object class that I parsed using the Twitter API. Despite using json_decode and json_encode, I am encountering errors. How can I successfully retrieve the elements? stdClass Object ( [statuses] => Arra ...

Uploading a file using AngularJs

When it comes to uploading an image or file using HTML tag in AngularJS, it seems that the tag is not supported. The solution? Create a custom directive. In my index.html page, I included the following code: <body ng-controller="myController"> ...