简体   繁体   中英

AngularJS error : TypeError: Cannot read property 'images' of undefined

AngularJS: v1.5.11

Im trying to display images from a JSON array.

Is this the proper way : $scope.mainImage = $scope.template.images[0].name; . This is the line in the error that it says cant read property of images .

My Controller in templates.js file:

.controller("TemplatesDetailsCtrl", ["$scope", "$routeParams", "$http", "$filter", function($scope, $routeParams, $http, $filter ){
    var templateId = $routeParams.templateID;
    $http.get("json/templates.json").success(function(data){
        $scope.template = $filter("filter")(data, function(d){
            return d.id == templateId;
        })[0];
        $scope.mainImage = $scope.template.images[0].name; //THIS IS LINE 30
    });
}]);

I'm trying to display the very first image from the array. So my HTML is:

<img class="img-full" src="img/{{mainImage}}">

Ben trying a lot and not able to display the image. Im getting this error: 在此处输入图片说明

Please help.

Seems like 'template' object is undefined. You can test for undefined before trying to use its properties :

if ($scope.template)
   $scope.mainImage = $scope.template.images[0].name; //THIS IS LINE 30

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