2

I've recently tried retrieving data from a JSON file using AngularJS. However I don't know how to do this; I've attempted to do this but it doesn't work, can someone please tell me where I'm going wrong?

<div ng-repeat="stuff in otherStuff">
  <p>Title: {{stuff.name}}</p>
  <p>Url: {{stuff.url}}</p>
</div>

DataController:

$scope.otherStuff = {};
jsonFactory.getOtherStuff()
  .then(function (response) {
    $scope.otherStuff = response.data.components;
  }, function (error) {
    console.error(error);
  });

jsonFactory:

angular.module('generatorMeanstackApp')
  .factory('jsonFactory', function ($q, $http) {
    return {
      getOtherStuff: function () {
        var deferred = $q.defer(),
          httpPromise = $http.get('data.json');

        httpPromise.then(function (response) {
          deferred.resolve(response);
        }, function (error) {
          console.error(error);
        });

        return deferred.promise;
      }
    };
  });

Example of my JSON data:

{
  "name": "Blogs",
  "url": "blogs.my-media-website.com/*",
  "dependsOn": ["Wordpress MU"],
  "technos": ["PHP", "Wordpress"],
  "host": { "Amazon": ["?"] }
},
2
  • what is JSON return from otherStuff? Commented Jun 8, 2015 at 12:03
  • Looks good to me at first glance. Any errors in the console? Commented Jun 8, 2015 at 12:05

1 Answer 1

0

In your controller, the reference to the data (via service) is nested too deep, it should be:

$scope.otherStuff = response.data;

Instead of:

$scope.otherStuff = response.data.components;

You can wrap your JSON in an array:

[
  {...},
  {...},
  {...}
]

Also, if you have scaffolded with yeoman, data.json needs to be in the app/ route. If it's outside of the route you will get a 404.

1
  • @benGshore Sorry, the scope binding should be $scope.otherStuff = response.data; - updated my answer. Commented Jun 8, 2015 at 13:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.