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.

3
  • 5
    Is there a really compelling reason why you can't simply write this into an angular service utilizing $http? Commented Oct 13, 2015 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? Commented Oct 13, 2015 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. 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 for more information. Commented Oct 13, 2015 at 20:51

1 Answer 1

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.
  });
}]);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.