waynev waynev - 1 month ago 21
AngularJS Question

Parse JSON array to object

I need to parse my JSON array to object in Angular, If I am correct but got no idea how to do that. I have read a few posts, and there many on the subject but for some reason I can not get it right.

Link to my JSON: http://wingfield.vmgdemo.co.za/webapi/view_stock_complete

//JS

app.controller('showRoom', function($scope, $http) {
$http.get('http://wingfield.vmgdemo.co.za/webapi/view_stock_complete').
then(function(response) {
$scope.view_stock_complete = response.data;
});
});


//HTML

<div class="container" ng-controller="showRoom">
<div><span>Variant: {{view_stock_complete.stock_id}}</span></div>
</div>

Answer

Your data is an array, so you'll need to loop over them using ng-repeat, or access the first entry using view_stock_complete[0]

(function(){
  'use strict';
  
  angular.module('test', [])
    .controller('TestController', TestController);
  
  TestController.$inject = ['$http'];
  
  function TestController($http) {
    var vm = this;
    
    vm.data = [];
    $http.get('http://wingfield.vmgdemo.co.za/webapi/view_stock_complete').then(function(response){
      vm.data = response.data;
    })
  }
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>

<div ng-app='test' ng-controller='TestController as tc'>
  <div ng-show="tc.data.length == 0">loading...</div>
  <div ng-repeat="car in tc.data">
    {{$index + 1}}. {{car.make}} {{car.series}}
  </div>
</div>