johncorser
johncorser

Reputation: 9842

How can I get JSON from an API into a view of my Angular app?

I have a JSON object that is returning at

localhost:9000/api/

and I'd like that JSON data to populate a view at

localhost:9000/#/query

I've got a route

.when('/query', {
  templateUrl: 'views/query.html',
  controller: 'QueryCtrl'
})

and a controller:

'use strict';

angular.module('myApp')
  .controller('QueryCtrl', ['$scope', 'Query', function ($scope, Query) {
    $scope.queries = Query.query();
  }]);

and the view:

<h1>Queries</h1>

<ul ng-repeat="query in queries">
  <li>{{query}}</li>
</ul>

it seems that either "queries" is empty though, or else the view is just not properly connected to the controller.

The app.js also has this factory:

app.factory('Query', ['$resource', function($resource) {
  return $resource('/api', null, {
    'update': { method:'PUT' }
  }); 
}]);

The JSON object itself looks like this:

[{"tablename":"acc_logs"},{"tablename":"accounts"},{"tablename":"cat_logs"},{"tablename":"err_logs"},{"tablename":"exp_logs"},{"tablename":"pp_logs"},{"tablename":"sec_logs"},{"tablename":"stl_logs"},{"tablename":"tim_logs"},{"tablename":"tom_logs"},{"tablename":"usage_logs"}]

I can see the JSON string at /api, but when I go to /#/query, it is just an empty list.

How can I connect these? What mistake have I made?

EDIT: Thanks for all the help everyone. I forgot to add my controller javascript in index.html. Rookie mistake, took an hour to fix.

Upvotes: 1

Views: 79

Answers (2)

D.Evangelista
D.Evangelista

Reputation: 6541

As I pointed in the comment, you should change $scope.query = Query.query(); to $scope.queries = Query.query();, as you are using ng-repeat over queries.

However, there are another error. You must change

app.factory('Query', ['$resource', function($resource) {
  return $resource('/api', null, {
    'update': { method:'PUT' }
  }); 
}]);

to

app.factory('Query', ['$resource', function($resource) {
  return $resource('/api/query', null, {
    'update': { method:'PUT' }
  }); 
}]);

When you call Query.query() you are requesting a HTTP GET to /api, while you want to request to /api/query.

Upvotes: 1

felipekm
felipekm

Reputation: 2910

I'm seeing that you are calling the Query object that seems to be unavailable, try:

angular.module('myApp')
  .controller('QueryCtrl', ['$scope', 'Query', function ($scope, Group) {
    $scope.query = Group.query();

Hope this helps.

Upvotes: 1

Related Questions