0

I have the following code, where I am trying to print the value of Bitcoin after getting it from the coinmarketcap REST API, using the axios library. Although the value is written fine in console, the text box remains empty. What mistake am I doing here?

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  function get_btc_value(){
    // return this promise
    return axios.get('https://api.coinmarketcap.com/v1/ticker/bitcoin/')
.then((data)=>{
      console.log(data.data[0].price_usd)
      return data.data[0].price_usd
    })
  }

  get_btc_value().then(data => $scope.myVar = data)
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

<input ng-value="myVar">

</div>

</body>
</html>
georgeawg
  • 48,608
  • 13
  • 72
  • 95
MetallicPriest
  • 29,191
  • 52
  • 200
  • 356

1 Answers1

2

The success callback of get_btc_value happens outside Angular. So maybe use $scope.$apply() or $scope.$digest() to trigger the watches. so textbox will get updated.


 get_btc_value().then(data => {
     $scope.myVar = data;
     $scope.$apply();
 }) 
georgeawg
  • 48,608
  • 13
  • 72
  • 95