user5000005
user5000005

Reputation:

AngularJS - Can't Display Content from JSON

I'm just starting with AngularJS and am having an issue using {{ expressions }} to pull data from JSON that I am getting with $http.get. The JSON object is coming through fine, as I was able to log it to the console. But when I try to display it in my view.html the expressions are empty. Maybe it's just something small, but I can't figure it out.

Code snippets below

Routing Snippet:

$routeProvider
.when('/contacts/:contactId', {
     controller: 'ContactController',
     templateUrl: 'js/views/contact.html'
})
.otherwise({
     redirectTo: '/'
});

Controller:

app.controller('ContactController', ['$scope', '$routeParams', '$http',
function($scope, $routeParams, $http) {
    $http.get($routeParams.contactId + '.json').success(function(data) {
        $scope.detail = data;
    })
    .error(function(data) {
        return data;
        console.log("Failed to get data")
    });
    $scope.pageClass = 'contact-screen';

}]);

Piece of the contact.html view:

<div class="text-container">
        <h2 class="name"> {{ detail.name }} </h2>
        <h3 class="subtitle"> "{{ detail.subtitle }}" </h3>
</div>

Upvotes: 1

Views: 357

Answers (1)

charlietfl
charlietfl

Reputation: 171669

You have an array containing an object for your data , not a single object as your code would currently indicate.

To show just one item as you currently have in view:

$scope.detail = data[0];

But since you will likely have more than one leave the controller the same and use ng-repeat to iterate over the array

<div class="text-container" ng-repeat="item in detail">
        <h2 class="name"> {{ item.name }} </h2>
        <h3 class="subtitle"> "{{ item.subtitle }}" </h3>
</div>

Alternatively since you have :contactId in url, change back end to return a single object and leave your code all the same

Upvotes: 1

Related Questions