0

I have the following javascript file called script.js with a jQuery function:

function getData(a, b) {

var d = [];

while (a <= b)
{
    $.ajax({
        url: "someurl",
        dataType: 'json',
        success: function (data) {
            d.push(data.rates);
        },
        error: function (err) {
            console.log(err);
        }
    });
    a+=1;
}

$(document).ajaxStop(function () {
    console.log("AJAX STOP");
    return d;
}); }

Explanation:
I fill the array d in a while loop with some information I get as a response from server someurl. I would like to pass this array to my controller called MainController.js. How do I do this? I would like to have a property in my controller, for example $scope.dataFromAjax, and it has to be equal to the final form of array d from ajax().
(something like $scope.dataFromAjax = d).
Thank you.

peech
  • 931
  • 3
  • 12
  • 23
  • 5
    Is there a really compelling reason why you can't simply write this into an angular service utilizing `$http`? – David L Oct 13 '15 at 20:42
  • not at all, I've been more familar with jQuery. can you please write me a short sample on how to do this? – peech Oct 13 '15 at 20:45
  • 2
    There are plenty of examples on how to use the `$http` service in AngularJS, not the least of which is the [AngularJS documentation for the service](https://docs.angularjs.org/api/ng/service/$http). Generally, you'll be hard-pressed to find a good use case for having jQuery + AngularJS unless you need to support legacy code. [Check out this post](http://stackoverflow.com/questions/14994391/thinking-in-angularjs-if-i-have-a-jquery-background) for more information. – Caleb Williams Oct 13 '15 at 20:51

1 Answers1

1

By using Angular's $http you can have a service that gets the data for you which you can inject into any controller, factory, directive, etc that you need to access your data.

app.service('dataService', ['$http', function ($http) {
  return {
    getSomething: function () {
      return $http.get('someurl');
    },
    getSomethingElse: function () {
      return $http.get('someotherurl');
    }
  }
}]);

app.controller("yourController", ['$scope', 'dataService', function ($scope, dataService) {
  dataService.getSomething().success(function(dataResults) {
    $scope.data = dataResults; // This is available as soon as the promise (get) is resolved.
  });
}]);
buzzsaw
  • 1,476
  • 1
  • 10
  • 14