Anton Anton - 2 months ago 18
AngularJS Question

Pass data from JSONP callback function to Angular controller

I have JSONP request that callbacks function outside Angular Controller. How can I return data from that function back to Controller? Or maybe there's a way to callback function inside Controller?

Adding '?callback=JSON_CALLBACK' don't fire success promise. I think it's because JSONP response wraped in function call:
CBR_XML_Daily_Ru({"Date":"2016-10-06T00:00:00+00:00" ... });

<div ng-controller='myCtrl' ng-app='myApp'>
<input type=text ng-model='divForCharCode'></input>
<div id='div1'></div>
</div>

<script>CBR_XML_Daily_Ru = function(data) {
document.getElementById("div1").innerHTML = data.Valute.EUR.CharCode;

};

var myApp = angular.module('myApp', [])
.controller('myCtrl', myCtrl);

function myCtrl($scope,$http) {
$scope.divForCharCode = ' need to place EUR here!';
$http.jsonp('https://www.cbr-xml-daily.ru/daily_jsonp.js');
};</script>


https://plnkr.co/edit/hKdXf7MxAhnU8aMFqPUV

Answer

i came up this solution after searching and trying ,in your case this solution is better than other solutions that use angular.element(....).scope() because here we use angular service $window while in (angular.element().scope) we use something may be disabled in some angular mode, check this.

CBR_XML_Daily_Ru = function(data) {
  window.angularJsonpCallBackDefindInController(data);

};

var myApp = angular.module('myApp', []).controller('myCtrl', myCtrl);

function myCtrl($scope, $http,$window) {
  var self = this;

  $http.jsonp('https://www.cbr-xml-daily.ru/daily_jsonp.js?callback=JSON_CALLBACK');
  $window.angularJsonpCallBackDefindInController = function (data) {
      //u can do anything here, you are in the controller, and in the same time this function in the window object and get called from anywhere even in jquery 
     self.divForCharCode = data.Valute.EUR.CharCode;
  };
}

you can also use this way to execute function in controller from jquery "scope":

CBR_XML_Daily_Ru = function(data) {
  angular.element("#controllerDivId").controller().angularJsonpCallBackDefindInController(data);

};

var myApp = angular.module('myApp', []).controller('myCtrl', myCtrl);

function myCtrl($scope, $http,$window) {
  var self = this;

  $http.jsonp('https://www.cbr-xml-daily.ru/daily_jsonp.js?callback=JSON_CALLBACK');
  self.angularJsonpCallBackDefindInController = function (data) {
     self.divForCharCode = data.Valute.EUR.CharCode;
  };
}

this is the html (you need to include jquery to use the second solution)

<html>

<head>
  <script src="jquery-3.1.1.min.js"></script>
  <script src="angular.min.js"></script>
  <!--<link rel="stylesheet" href="style.css" />-->
  <script src="jsnopstuff.js"></script>
</head>

<body>
    <div id="controllerDivId" ng-controller='myCtrl as ctrl' ng-app='myApp'>
        <input type=text ng-model='ctrl.divForCharCode'>
        <div id='div1'></div>
    </div>

</body>
</html>