114

I have what I think is probably a very obvious question, but I couldn't find an answer anywhere.

I am just trying to load some JSON data from my server into the client. Right now, I am using JQuery to load it with an AJAX call (code below).

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

This is located in the html file. It works so far, but the issue is that I want to use AngularJS. Now, while Angular CAN use the variables, i cannot load the whole thing into a variable so I can use a for each loop. This seems to be related to the "$Scope", which is usually located in the .js file.

The problem is that I cannot load code from other pages into a .js file. Every example of Angular only shows stuff like this:

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

So, this is useful, if I A) Want to type all of this by hand, AND B) If I know in advance what all my data is...

I don't know in advance (the data is dynamic) and I don't want to type it.

So, when I tried to change the AJAX call to Angular using $Resource, it doesn't seem to work. Maybe I can't figure it out, but it is a relatively simple GET request for JSON data.

tl:dr I can't get AJAX calls to work in order to load external data into an angular model.

1
  • 3
    Can we see your attempt at using $Resource? It should work, so perhaps it's easiest if we help you debug that... Oct 23, 2012 at 11:40

3 Answers 3

189

As Kris mentions, you can use the $resource service to interact with the server, but I get the impression you are beginning your journey with Angular - I was there last week - so I recommend to start experimenting directly with the $http service. In this case you can call its get method.

If you have the following JSON

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

You can load it like this

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

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

The get method returns a promise object which first argument is a success callback and the second an error callback.

When you add $http as a parameter of a function Angular does it magic and injects the $http resource into your controller.

I've put some examples here

6
  • thanks so much, I did end up using the $http service instead...albeit a slightly different way... code $http.get('/json').success( function(response){ $scope.reports = response; getData(); code what is interesting to me, is the promise object...I really want to learn more about that. I love the idea of it. The other problem I have been having is basically running a loop on the ajax request so i can constantly "automagically" refresh the page. $timeout has not been working for me.
    – MJR_III
    Oct 25, 2012 at 10:13
  • 1
    I believe it should be $scope.todos = res; instead of res.data.
    – Anoyz
    Nov 14, 2013 at 21:22
  • The response object has four properties: config, data, headers and status. The values in the data property are what you want.
    – jaime
    Nov 14, 2013 at 22:25
  • 1
    worth having a $scope.todos = []; before the http request, so you at least have a default empty structure so as not to throw errors in your template.
    – S..
    Apr 15, 2014 at 17:16
  • 1
    re: $scope.todos = res; or $scope.todos = res.data; -- the difference is whether you are in a .then(response) or in a .success(result) The .success is given response.data while the .then is given the entire response. May 12, 2015 at 23:53
28

Here's a simple example of how to load JSON data into an Angular model.

I have a JSON 'GET' web service which returns a list of Customer details, from an online copy of Microsoft's Northwind SQL Server database.

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

It returns some JSON data which looks like this:

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

..and I want to populate a drop down list with this data, to look like this...

Angular screenshot

I want the text of each item to come from the "CompanyName" field, and the ID to come from the "CustomerID" fields.

How would I do it ?

My Angular controller would look like this:

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

... which fills a "listOfCustomers" variable with this set of JSON data.

Then, in my HTML page, I'd use this:

<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>

And that's it. We can now see a list of our JSON data on a web page, ready to be used.

The key to this is in the "ng-options" tag:

customer.CustomerID as customer.CompanyName for customer in listOfCustomers

It's a strange syntax to get your head around !

When the user selects an item in this list, the "$scope.selectedCustomer" variable will be set to the ID (the CustomerID field) of that Customer record.

The full script for this example can be found here:

JSON data with Angular

Mike

4
  • Does this actually work? Your JSON is invalid (the keys are not in quotation marks). Don't you get errors? Nov 13, 2014 at 22:01
  • Sorry, you're right. I took the screenshot above from Google Chrome with the excellent JSONView addin installed (so you can view the JSON in a nicely formatted way). But yes, the JSON from my web service is valid. If you click on the link in my article, you can view a live version of this code. Nov 14, 2014 at 8:22
  • Does it work? i think it should be data.GetAllCustomersResult
    – ihappyk
    Sep 2, 2015 at 4:51
  • Oops, you're absolutely right. I had changed the web service to include wrapping the JSON results in "GetAllCustomersResult", so yes, this is needed. I've updated the code sample. Thanks for the heads-up. Sep 2, 2015 at 7:02
0

I use following code, found somewhere in the internet don't remember the source though.

    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);

Not the answer you're looking for? Browse other questions tagged or ask your own question.