jonny pixel
jonny pixel

Reputation: 267

AngularJs. Reading JSON properly

I am noob in AngularJS, but trying to learn my way through it.

I have the following controller. It get's JSON file based on the URL.

app.controller('PortfolioItemCtrl', ['$scope', '$routeParams', '$http',
    function($scope, $routeParams, $http) {
        $http.get('pages/portfolio/' + $routeParams.itemId + '.json').
            success(function(data) {
                $scope.item = data;
        });
}]);

The problem that I seems not able to read this JSON as I expect.

Here how I am trying to fetch this data in my HTML:

      <div ng-controller="PortfolioItemCtrl">
        <h1>{{item.cat}}</h1>
        <p>{{item.desc}}</p>
      </div>

And my JSON looks like this

{
    "item_1": {
        "id":"1",
        "cat": "Web design",
        "desc": "Online magazine design for <em> \"Calcus\" <\/em> brand",
        "images": [
            "img/portfolio-item-1.jpg",
            "img/portfolio-item-2.jpg"
        ]
    }
}

But it does not render any data. However if I put {{item}} in the HTML, I can see that it fetches the JSON file.

Please help me to understand what I am doing wrong. I would appreciate your explanation and some direct advice on what to focus in learning AngularJS in respect to this particular topic.

Upvotes: 0

Views: 53

Answers (2)

dddd1919
dddd1919

Reputation: 888

Looks like your JSON data is

{ 
    $scope.item = {
        "item_1": {
            "id":"1",
            "cat": "Web design",
            "desc": "Online magazine design for <em> \"Calcus\" <\/em> brand",
            "images": [
                "img/portfolio-item-1.jpg",
                "img/portfolio-item-2.jpg"
            ]
        }
    }
}

So just call {{item.item_1.cat}} instead {{item.cat}} with your template

Upvotes: 2

alpinescrambler
alpinescrambler

Reputation: 1954

Try

   <div ng-controller="PortfolioItemCtrl">
    <h1>{{item.item_1.cat}}</h1>
    <p>{{item.item_1.desc}}</p>
  </div>

Upvotes: 2

Related Questions