1

I have a simple view where a bunch of JSON data gets displayed. The problem I'm facing is when I try to display the directly from within the factory the data is displayed but the same data when access via a $http.get request is not getting displayed! The data is being fetched but the JSON format is changing during the fetch request.

My controller code is as below:

angular.module('ngCribs')
.controller('cribsController', function($scope, cribsFactory) {
  $scope.cribs;

  cribsFactory.getCribs().then(function(data) {
    console.log(data);
    $scope.cribs = data;
  }, function(data) {
    console.log(data);
  });

});

My Factory code:

angular.module('ngCribs')
.factory('cribsFactory', function($http) {

  function getCribs() {
    return $http.get('data.json');
  }

  return {
    getCribs: getCribs
  };

});

The JSON object as I have created:

[
  {
    "type": "Condo",
    "price": 220000,
    "address": "213 Grove Street",
    "description": "Excellent place, really nice"
  },
  {
    "type": "House",
    "price": 410000,
    "address": "7823 Winding Way",
    "description": "Excellent place, really nice and beautiful"
  },
  {
    "type": "Duplex",
    "price": 395000,
    "address": "2834 River Lane",
    "description": "Great, really nice"
  }
]

What is getting outputted on the console:

Here is a snapshot of the consoled object

Here is a plunker link to my progress so far

https://plnkr.co/edit/GTZJC2cCCzE1KfLAD5wF?p=preview

As you can see in the plunker the data isn't getting displayed. Please help and guide me as to where I'm making a mistake.

Thanks.

4
  • 2
    use data.data to get the api response. data.data is your array object. Replace this line as `$scope.cribs = data.data;' Commented Jan 18, 2017 at 3:09
  • See docs.angularjs.org/api/ng/service/$http#general-usage Commented Jan 18, 2017 at 3:16
  • plnkr.co/edit/ZbvW23Sb7qavtQI2ALsa?p=preview Commented Jan 18, 2017 at 3:38
  • As suggested by @Nhan, just update your code to get the data, then I think it should work $scope.cribs = data.data; Commented Jan 18, 2017 at 4:45

2 Answers 2

1

In cribsController.js, you are getting the whole response object, change it to data.data to access the response data only.

cribsFactory.getCribs().then(function(data) {
  console.log(data);
  $scope.cribs = data.data;
}, function(data) {
  console.log(data);
});
Sign up to request clarification or add additional context in comments.

Comments

0

Change <div class="well" ng-repeat="crib in cribs">

To

<div class="well" ng-repeat="crib in cribs.data">

You should use data.data in order for you to loop.

Comments

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.