简体   繁体   中英

How to properly iterate over a JSON file in Angular JS?

I'm trying to create a list using angular and my data comes from a json file.I'm unable make it work.

My HTML looks like this

     <ion-list>
     <div ng-repeat="item in artists" class="card">
      <ion-item class="item-avatar">
      <img src="https://api.adorable.io/avatars/400/">
      <h2>{{item.name}}</h2>
      <p>{{item.reknown}}</p>
      </ion-item>
     </div>
     </ion-list>

And my angular code is this

.controller('listController',['$scope','$http',function($scope, $http){
$http.get('js/data.json').success(function(data){
  $scope.artists = data;
});
}])

and the json data looks like this

{
"artists": [
    {

        "name": "Barot Bellingham",
        "reknown": "Royal Academy of Painting and Sculpture"
    },
    {


        "name": "Jonathan G. Ferrar II",
        "reknown": "Artist to Watch in 2012"
    },
    {

        "name": "Hillary Hewitt Goldwynn-Post",
        "reknown": "New York University"
    } 
]
}

My ng-repeat is somehow not working. Maybe i'm unable to iterate properly over the array of objects. Can you help me out ?

You should access the artists array from the json, It will be like this,

app.controller("listController", ["$scope","$http",
    function($scope,$http) {
       $http.get('test.json').then(function (response){
                $scope.artists = response.data.artists;
                console.log(data)
        });

}]);

DEMO

Here is the plunkr for your problem

Your controller must be

app.controller('listController', ['$scope', '$http', function($scope, $http) {
  $http.get('data.json').success(function(data) {
    $scope.artists = data.artists;
  });

Your HTML must be

<div ng-repeat="item in artists" class="card">
      <ion-item class="item-avatar">
      <img src="https://api.adorable.io/avatars/400/">
      <h2>{{item.name}}</h2>
      <p>{{item.reknown}}</p>
      </ion-item>
</div>

Try:

$http.get('js/data.json').success(function(data){
        $scope.artists = data['artists'];
        console.log($scope.artists);
});

Hey just Try to get the json in php and assigned to the variable you want

<?php $json = file_get_contents('your path od json file'.'.json');
      $result =json_decode($json,true);
?>
<script type="text/javascript">
  var inputjson = <?php echo json_encode($result); ?>;
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM