[英]Angular $http request not returning Rails resource
I'd like to get a JSON object of all the posts in my database. 我想获取数据库中所有帖子的JSON对象。
Here's the module: 这是模块:
angular
.module('AngularRails', [
'ngRoute',
'templates'
]).config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'home.html',
controller: 'HomeCtrl'
});
});
A controller: 控制器:
angular.module('AngularRails')
.controller('PostsController', function($scope, $http) {
var posts = $http.get('/posts.json').success(function(data){
return data;
});
$scope.posts = posts;
});
The view: 风景:
<h1>The Home View!</h1>
<ul>
<li ng-repeat='post in posts'>
{{ post.title }}
</li>
</ul>
When I check the console, I can see that the request is made to the specified URL (and can see the JSON I want), but it's buried deeply within some large object. 当我检查控制台时,可以看到请求是对指定的URL发出的(并且可以看到我想要的JSON),但是它被深深地埋在某个大对象中。
How can I display the posts in an unordered list? 如何在无序列表中显示帖子?
Edit 编辑
As per Dan's suggestion, I've changed the controller to this: 根据Dan的建议,我将控制器更改为:
angular.module('AngularRails')
.controller('PostsController', function($scope, $http) {
$http.get('/posts.json').success(function(data) {
$scope.posts = data;
});
});
No cigar. 没有雪茄。
The data you are looking for will be passed as a parameter to the success callback from $http
. 您要查找的数据将从
$http
作为参数传递给成功回调。 $scope.posts
in your example is the entire http object. 您的示例中的
$scope.posts
是整个http对象。 Try something like this: 尝试这样的事情:
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
});
Example 例
Rails controller: 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 controller: Angualr控制器:
$http.get('http://localhost:3000/posts/list.json').success (data) ->
$scope.posts = data.posts
console.log $scope.posts // ["post1", "post2", "post3", "post4"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.