【问题标题】:How to properly iterate over a JSON file in Angular JS?如何正确迭代 Angular JS 中的 JSON 文件?
【发布时间】:2017-03-12 18:56:36
【问题描述】:

我正在尝试使用 Angular 创建一个列表,而我的数据来自一个 json 文件。我无法让它工作。

我的 HTML 看起来像这样

     <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>

我的角度代码是这样的

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

json 数据是这样的

{
"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"
    } 
]
}

我的 ng-repeat 不知何故无法正常工作。也许我无法正确迭代对象数组。你能帮帮我吗?

【问题讨论】:

  • 确保$scope.artists 是一个对象数组。也许你应该做$scope.artists = data.artists

标签: javascript angularjs json ionic-framework angularjs-ng-repeat


【解决方案1】:

嘿嘿只是尝试在php中获取json并分配给你想要的变量

<?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>

【讨论】:

    【解决方案2】:

    试试:

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

    【讨论】:

      【解决方案3】:

      这里是plunkr 解决您的问题

      您的控制器必须是

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

      您的 HTML 必须是

      <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>
      

      【讨论】:

        【解决方案4】:

        你应该从 json 中访问艺术家数组,它会是这样的,

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

        DEMO

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-06-12
          • 1970-01-01
          • 1970-01-01
          • 2016-01-14
          • 2012-02-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多