从angularjs中的网页上的本地JSON文件访问图像

时间:2018-06-07 18:22:22

标签: angularjs json ajax

我哪里错了?

我想从网页上的datahl.json文件访问图像但无法访问它们。请检查代码并帮助我。 如果可能,请将解决方案提交给plunker编辑器。

的index.html

        <div class="col-sm-4" ng-repeat = "hbl in hbls">
            <div class="thumbnail" ng-repeat = "h in hbl.data_list" 
                 style="width:100%;">
              <img ng-src="{{h.img}}" alt="" style="height:50vh;">
                 <div class="caption">   
                    <p><strong>{{h.name}}</strong></p>
                </div>
            </div>
        </div> 

app.js 这是我的js代码

 var app = angular.module('hostellApp', []);
app.controller('hostellController', function($scope, hblsFactory){
    $scope.hbls;

    hblsFactory.getHbls().then(function(response){
       $scope.hbls = response.data; 
    });

    $scope.sayHello = function(){
        console.log("Hello");
    }
});

    app.factory('hblsFactory', function($http){

        function getHbls(){
            return $http.get('datahl.json');
        }

        return {
            getHbls: getHbls
        }
    });    

datahl.json 这是我的本地JSON文件

`   {

    "view_type": 5,
    "title": "Hostels By Locality",
    "position": 5,
    "data_list":
   [

        {
            "img": "https://s3.us-east-2.amazonaws.com/images-city- 
                    teens/IMG_20180526_1139570.8091572935412125.jpg",
            "name": "Mahavir Nagar"
        },
        {
            "img": "https://graph.facebook.com/1666751513414902/picture? 
                          type=large",
            "name": null
        },
        {
            "img": "https://s3.us-east-2.amazonaws.com/images-city- 
                            teens/cropped1148015742983667713.jpg",
            "name": "New Rajiv Gandhi"
        },
        {
            "img": "https://s3.us-east-2.amazonaws.com/images-city- 
                         teens/cropped998427941.jpg",
            "name": "Jawahar Nagar"
        }

    ]
}`

1 个答案:

答案 0 :(得分:0)

从JSON文件获取的数据不是数组而是对象。这意味着您只需要一个ng-repeat

将您的第一个ng-repeat更改为ng-repeat="h in hbls.data_list"(在hbl中添加's')并删除您的第二个ng-repeat

工作人员:https://plnkr.co/edit/OOd1M1dNFjSB7uaqZZB6?p=preview