如何将json加载到我的angularjs ng-model中?

时间:2012-10-22 22:24:29

标签: javascript ajax angularjs model

我认为这可能是一个非常明显的问题,但我无法在任何地方找到答案。

我只是想将一些JSON数据从我的服务器加载到客户端。现在,我正在使用JQuery通过AJAX调用加载它(下面的代码)。

<script type="text/javascript">
var global = new Array();
$.ajax({
    url: "/json",
    success: function(reports){
        global = reports;
        return global;
        }
    });
</script>

这位于html文件中。它到目前为止工作,但问题是我想使用AngularJS。现在,当Angular CAN使用变量时,我无法将整个事物加载到变量中,因此我可以为每个循环使用a。这似乎与“$ Scope”有关,它通常位于.js文件中。

问题是我无法将其他页面的代码加载到.js文件中。 Angular的每个例子都只显示如下内容:

function TodoCtrl($scope) {
  $scope.todos = [
    {text:'learn angular', done:true},
    {text:'build an angular app', done:false}];

所以,如果我,这很有用 A)想要手动输入所有这些,AND B)如果我事先知道我的所有数据是什么......

我事先不知道(数据是动态的),我不想输入它。

因此,当我尝试使用$ Resource将AJAX调用更改为Angular时,它似乎不起作用。也许我无法弄明白,但这是对JSON数据的一个相对简单的GET请求。

tl:dr我无法让AJAX调用工作,以便将外部数据加载到角度模型中。

3 个答案:

答案 0 :(得分:189)

正如Kris所提到的,您可以使用$resource服务与服务器进行互动,但我得到的印象是您开始使用Angular旅行 - 我上周就在那里 - 所以我建议您直接尝试$http服务。在这种情况下,您可以调用其get方法。

如果您有以下JSON

[{ "text":"learn angular", "done":true },
 { "text":"build an angular app", "done":false},
 { "text":"something", "done":false },
 { "text":"another todo", "done":true }]

您可以像这样加载

var App = angular.module('App', []);

App.controller('TodoCtrl', function($scope, $http) {
  $http.get('todos.json')
       .then(function(res){
          $scope.todos = res.data;                
        });
});

get方法返回 promise 对象 第一个参数是成功回调,第二个参数是错误 回调。

当您添加$http作为函数的参数时,Angular会使它变得神奇 并将$http资源注入您的控制器。

我在这里举了一些例子

答案 1 :(得分:28)

这是一个如何将JSON数据加载到Angular模型中的简单示例。

我有一个JSON&#39; GET&#39; Web服务,它从Microsoft的Northwind SQL Server 数据库的在线副本返回客户详细信息列表。

http://www.iNorthwind.com/Service1.svc/getAllCustomers

它返回一些如下所示的JSON数据:

{ 
    "GetAllCustomersResult" : 
        [
            {
              "CompanyName": "Alfreds Futterkiste",
              "CustomerID": "ALFKI"
            },
            {
              "CompanyName": "Ana Trujillo Emparedados y helados",
              "CustomerID": "ANATR"
            },
            {
              "CompanyName": "Antonio Moreno Taquería",
              "CustomerID": "ANTON"
            }
        ]
    }

..我想用这些数据填充下拉列表,看起来像这样......

Angular screenshot

我希望每个项目的文字来自&#34; CompanyName&#34;字段,以及来自&#34; CustomerID&#34;领域。

我该怎么做?

My Angular控制器看起来像这样:

function MikesAngularController($scope, $http) {

    $scope.listOfCustomers = null;

    $http.get('http://www.iNorthwind.com/Service1.svc/getAllCustomers')
         .success(function (data) {
             $scope.listOfCustomers = data.GetAllCustomersResult;
         })
         .error(function (data, status, headers, config) {
             //  Do some error handling here
         });
}

...填写&#34; listOfCustomers&#34;这组JSON数据的变量。

然后,在我的HTML页面中,我将使用它:

<div ng-controller='MikesAngularController'>
    <span>Please select a customer:</span>
    <select ng-model="selectedCustomer" ng-options="customer.CustomerID as customer.CompanyName for customer in listOfCustomers" style="width:350px;"></select>
</div>

就是这样。我们现在可以在网页上看到我们的JSON数据列表,可供使用。

关键在于&#34; ng-options&#34;标记:

customer.CustomerID as customer.CompanyName for customer in listOfCustomers

这是一个奇怪的语法,让你的头脑!

当用户选择此列表中的项目时,&#34; $ scope.selectedCustomer&#34;变量将设置为该客户记录的ID(CustomerID字段)。

此示例的完整脚本可在此处找到:

JSON data with Angular

麦克

答案 2 :(得分:0)

我使用下面的代码,发现在互联网的某个地方不记得来源。

    var allText;
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function () {
        if (rawFile.readyState === 4) {
            if (rawFile.status === 200 || rawFile.status == 0) {
                allText = rawFile.responseText;
            }
        }
    }
    rawFile.send(null);
    return JSON.parse(allText);