简体   繁体   English

将数据从jQuery.ajax()传递到角度控制器?

[英]Pass data from jQuery.ajax() to angular controller?

I have the following javascript file called script.js with a jQuery function: 我有一个带有jQuery函数的名为script.js的以下javascript文件:

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 . 我在while循环中用来自服务器someurl的响应获得的一些信息填充数组d I would like to pass this array to my controller called MainController.js . 我想将此数组传递给名为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(). 我想在我的控制器中有一个属性,例如$ scope.dataFromAjax,它必须等于ajax()中数组d的最终形式。
(something like $scope.dataFromAjax = d ). (类似于$scope.dataFromAjax = d )。
Thank you. 谢谢。

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. 通过使用Angular的$ http,您可以拥有一个为您获取数据的服务,您可以将其注入到访问数据所需的任何控制器,工厂,指令等中。

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.
  });
}]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM