2014-11-22 99 views
1

我想要获取数据库中所有帖子的JSON对象。

这里的模块:

angular 
.module('AngularRails', [ 
    'ngRoute', 
    'templates' 
    ]).config(function($routeProvider) { 
     $routeProvider 
      .when('/', { 
      templateUrl: 'home.html', 
      controller: 'HomeCtrl' 
      }); 
    }); 

控制器:

angular.module('AngularRails') 
    .controller('PostsController', function($scope, $http) { 
    var posts = $http.get('/posts.json').success(function(data){ 
     return data; 
    }); 

    $scope.posts = posts; 
    }); 

的视图:

<h1>The Home View!</h1> 

<ul> 
    <li ng-repeat='post in posts'> 
    {{ post.title }} 
    </li> 
</ul> 

当我检查控制台,我可以看到,该请求是由指定的URL(并且可以看到我想要的JSON),但是它深深地埋在一些大对象内。

如何在无序列表中显示帖子?

编辑

按照丹的建议,我已经改变了控制器这样的:

angular.module('AngularRails') 
    .controller('PostsController', function($scope, $http) { 
    $http.get('/posts.json').success(function(data) { 
     $scope.posts = data; 
    }); 
    }); 

没有雪茄。

+0

能否请您发布回应? – cthulhu 2014-11-22 13:49:52

回答

2

您正在查找的数据将作为参数传递给$http成功回调。在你的例子中$scope.posts是整个http对象。尝试是这样的:

angular.module('AngularRails').controller('PostsController', function($scope, $http) { 
    $http.get('/posts.json').success(function(postData, status, headers, config){ 
     $scope.posts = postData; // this is the JSON from the web request 
    }); 

    // $scope.posts = posts; <-- this was the $http promise object 
}); 

Rails的控制器:

def list 
    posts = { posts: %w(post1 post2 post3 post4) } # Or ActiveRecord query etc... 

    respond_to do |format| 
    format.json { render json: posts } 
    end 
end 

Angualr控制器:

$http.get('http://localhost:3000/posts/list.json').success (data) -> 
    $scope.posts = data.posts 
    console.log $scope.posts // ["post1", "post2", "post3", "post4"] 
+0

嘿,丹!感谢您的建议,但这似乎不起作用。我用我试过的东西更新了原文。我确实试图使用其余的参数,但我很确定它可以缩短为一个(纠正我,如果我错了)。 – 2014-11-22 09:04:17

+0

@DylanRichards我用一个更好的例子更新了答案,它可能会有助于看到你在轨道上做什么,但这应该有所帮助。你也是正确的,成功回调中的额外参数是不需要的 - 这只是为了说明。让我知道如果帮助! (这里的js是coffeescript!) – 2014-11-22 18:27:57