Somename
Somename

Reputation: 3434

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: enter image description here

Please help.

Upvotes: 0

Views: 909

Answers (1)

Roh&#236;t J&#237;ndal
Roh&#236;t J&#237;ndal

Reputation: 27192

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

Upvotes: 1

Related Questions