How to load json into my angular.js ng-model?

MJR_III picture MJR_III · Oct 23, 2012 · Viewed 256.1k times · Source

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.

Answer

jaime picture jaime · Oct 23, 2012

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