Search code examples
javascriptangularjsamazon-s3cross-domainjsonp

How to load JSON file from S3 using Angular $http.jsonp


I am loading JSON file from S3. File is loading successfully but problem is, I cannot access AnglarJS modules($scope, services and etc) in my callback function because it is written outside angularJS. Is there a way to access $scope in my callback?

AngularJS code

var url = "http://my_s3_url/abc/v1/klm/my.json"

$http.jsonp(url);

my.json

jsonp_callback({name:"xyz",age:2})

callback

<script>
   function jsonp_callback(data) {
      console.log(data.name);
      // cannot access $scope here :(
   }
</script>

Solution

  • Hmm you are using $http so I guess angular is generally available.

    Is there a way to access $scope in my callback?
    If the script block is within the same document, then any scope is accessible by doing i.e. angular.element('body').scope().

    <script>
      function jsonp_callback(data) {
        console.log(data.name);
        
        // access $scope here :)
        var scope = angular.element('body').scope();
        scope.$apply(function() {
          scope.lastResult = data;
        });
      }
    </script>
    

    Element body is used only as an example. It might be adapted for any DOM element related to the target scope.