Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

I'm pretty new to angularjs, and getting a json result set that I'd like to display. I have the following;

Service:

var Post = function(data) {
    angular.extend(this, data);
}

Post.getAll = function() {
    return $http.get('/api/posts').then(function(response) {
        var Posts = [];
        for(var i = 0; i < response.data.length; i++) {
            Posts.push(new Post(response.data[i]));
        }
        return Posts;
    });
};

Controller method:

$scope.Posts = Posts.getAll();

html view:

<ul ng-repeat="post in Posts">
    <li>{{ post.title }}</li>
</ul>

The problem is that while everything repeats correctly, I cannot access the members of each object. eg: post.title or post.text does not display. However, if I use {{ post }} it displays the json for the entire result.

Where am I going wrong here?

Edit: I've just seen thanks to the comment below that if I use

post[0].title

It correctly displays, however is this the correct way to be displaying an array of json results? I'd prefer to use the correct method, vs the one that "just works".

share|improve this question
1  
Could it be the way you are accessing it? What does {{post}} show? – kubuntu Sep 24 '13 at 21:29
    
{{ post }} shows the json for that whole row, eg "{"0":{"title":"Test title","introduction":"test introduction.." I'm unsure about how I can transform the object so that I can bind {{ post.title }} or if there's another way I should be binding it. – Neophyte Sep 24 '13 at 21:36
    
From the way your data is returned, that (post[0].title) is the right approach. You could change the data source to remove the {"0": – kubuntu Sep 24 '13 at 21:45
1  
Yes, post[index].title is the correct way to bind to your JSON – Zack Argyle Sep 24 '13 at 21:45
    
Alright, thanks for the help! – Neophyte Sep 24 '13 at 21:49
up vote 0 down vote accepted

As per comments by ranru and Zack Argyle, I simply needed to add the index to post, eg: post[0].title.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.