Kevin
Kevin

Reputation: 437

Some problems with Angular JS and Javascript

I'm a newbie in Javascript and Angular JS programming and I'm trying to make a currency converter using Yahoo Finance API, but also I want to input directly the initial value in the script without clicking the button or pressing enter, so i figured that using Angular JS would be great. But it doesn't work properly and I think the problem might be in function calculate($scope). Please, can you help me?

<html ng-app>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  function httpGet(theUrl)
{
    var xmlHttp = null;
    xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", theUrl, false );
    xmlHttp.send( null );
    return xmlHttp.responseText;
}
function currencyConverter(currency_from,currency_to,currency_input){
var yql_base_url = "https://query.yahooapis.com/v1/public/yql";
var yql_query = 'select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20("'+currency_from+currency_to+'")';
var yql_query_url = yql_base_url + "?q=" + yql_query + "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
var http_response = httpGet(yql_query_url);
var http_response_json = JSON.parse(http_response);

return http_response_json.query.results.rate.Rate;
}

//The problem starts here?

function calculate($scope)
{
  $scope.total= function(){
var currency_from = "USD";
var currency_to = "INR";
var rate = currencyConverter(currency_from,currency_to,$scope.currency_input);
return rate;
};
}
  </script>
  <script src="js/angular.js"></script>
</head>
<body>
        <div ng-controller="calculate">
        <div style="float:left;">
        <form>
          <input type="text" ng-model="currency_input" value="0"/> = &nbsp;
        </form>
        </div>
        <div style="float:left">
        {{total()}}
      </div>
      </div>
        <div style="clear: both;"></div>

</body>
</html>

Upvotes: 1

Views: 148

Answers (4)

CDelaney
CDelaney

Reputation: 1248

Angular makes something like this much easier than what you're attempting. There's an $http service for performing a GET, for one, so you can leave out jquery and create something much simpler like ConverterService in my example.

Since your input is bound to a scope variable, you don't need to set value="0", simply set $scope.currency_input to your default value in your controller. I created a convert function on the scope, which will update the output whenever its called. It's called once at the bottom of the controller, but could be bound to a button in your html by simply doing something like this: <button ng-click="convert()">Convert value</button>

var app = angular.module('calc', []);

app.controller('MainCtrl', function($scope, ConverterService) {
  // default your currency input
  $scope.currency_input = 10;

  var currency_from = "USD";
  var currency_to = "INR";
  
  $scope.convert = function() {
    ConverterService.getConversions(currency_from, currency_to)
    .then(function(response) {
        // put your logic to convert the value here
        var convertedVal = null; // = $scope.currency_input * response.something etc...
    
        $scope.result = convertedVal;
    });
  };
  
  $scope.convert();// run once when the controller loads to get defaulted input conversion
});

app.factory('ConverterService', function($http) {
  return {
    getConversions: function(from, to, val) {
      var endpoint = ''; // build your endpoint here

      return $http.get(endpoint);
    }
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<html ng-app="calc">
<div ng-controller="MainCtrl">
  <input type="text" ng-model="currency_input">= {{result}}
</div>

</html>

Upvotes: 1

caiolopes
caiolopes

Reputation: 571

There are a few erros in your code using AngularJS. You forgot to start your application module and add a controller.

I made a few corrections and I tested, it is working:

<html ng-app="app">
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
</head>
<body>
        <div ng-controller="MyController">
        <div style="float:left;">
        <form>
          <input type="text" ng-model="currency_input" ng-change="total()" value="0"/> = &nbsp;
        </form>
        </div>
        <div style="float:left">
          {{ rate }}
        </div>
      </div>
        <div style="clear: both;"></div>

  <script>
  angular.module('app', [])
  .controller('MyController', function($scope, $http) {

    function currencyConverter(currency_from,currency_to) {
      var yql_base_url = "https://query.yahooapis.com/v1/public/yql";
      var yql_query = 'select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20("'+currency_from+currency_to+'")';
      var yql_query_url = yql_base_url + "?q=" + yql_query + "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
      $http.get(yql_query_url).then(function(response) {
        $scope.rate = $scope.currency_input*response.data.query.results.rate.Rate;
      });
    }

      $scope.total = function() {
      var currency_from = "USD";
      var currency_to = "INR";
      currencyConverter(currency_from, currency_to);
    };
  });
  </script>
</body>
</html>

I don't recommend you to use jquery to make http calls. Use $http instead!

Upvotes: 1

Chris Hermut
Chris Hermut

Reputation: 1758

You should take a look at services (https://docs.angularjs.org/guide/services).

With that you can just create a service and put all of your 'Yahoo' related functions in one place. Then just inject it into your directive/controller.

ex:

    .service('yahooRelatedLogicSrvc', function () {
      return {
          httpGet: function httpGet(theUrl) {
           var xmlHttp = null;
           xmlHttp = new XMLHttpRequest();
           xmlHttp.open( "GET", theUrl, false );
           xmlHttp.send( null );
           return xmlHttp.responseText;
        }
      }
    })
  .controller('sampleCtrl', function ($scope, yahooRelatedLogicSrvc) {
    var url = 'http://yahoo.com';

    $scope.httpGet = yahooRelatedLogicStvc.httpGet(url);
  }

And you can just put returns of your service functions as $scope properties etc. I really can see why you should use in line javascript in that scenario.

Upvotes: 1

toddmo
toddmo

Reputation: 22466

One problem, which should be the first to be corrected and go from there, is that you are referencing an angular concept $scope in your scripts before you actually declare the angular library.

To correct this, move your angular library script tag up above your other script tag (but below the jquery script tag.

Upvotes: 1

Related Questions