2014-11-22 4 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; 
    }); 

보기 : I 콘솔 검사시

<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

답변

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 
}); 

레일 컨트롤러 : 이런 식으로 뭔가를 시도

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

안녕하세요, 댄! 제안 해 주셔서 감사합니다. 그러나 이것이 효과가없는 것 같습니다. 나는 원래의 게시물을 내가 시도한 것으로 업데이트했다. 나는 나머지 매개 변수를 사용하려고 시도했지만 꽤 단축 될 수 있다고 확신한다. (틀렸다면 수정해라.) –

+0

@DylanRichards 더 좋은 예를 들어 대답을 업데이트 했으므로 레일 사이드에서 무엇을하고 있는지 보아도 도움이 될 수 있지만 도움이 될 것입니다. 또한 올바른지, 성공 콜백의 추가 매개 변수가 필요하지 않습니다. 이는 단지 설명을위한 것입니다. 도움이되는지 알려주세요! (여기서 js는 coffeescript입니다!) –

관련 문제