0

I have noticed that AngularJS requires the results in javascript from the back-end server.

The current server in the example returns angular.callbacks._0({"key": "value"}); with javascript headers. How to make the returns in the same format on Rails? Thanks!

AngularJS generates http://echo.jsontest.com/key/value?callback=angular.callbacks._0 link from that request by default

Here is my working example:

<!DOCTYPE html>
<html ng-app="Simple">
<body>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular-resource.min.js"></script>
<div ng-controller="SimpleController">    
    {{some_item.key}}
</div>
<script>
angular.module('Simple', ['ngResource']);
function SimpleController($scope, $resource) {
    $scope.simple = $resource('http://echo.jsontest.com/key/value',
        {callback:'JSON_CALLBACK'},
        {get:{method:'JSONP'}}
    );
    $scope.some_item = $scope.simple.get();
    console.log($scope.some_item.key);
}   
</script>
</body>
</html>

1 Answer 1

1

As long as you have a RESTful controller responding to JSON it will work fine.

class ArticlesController < ApplicationController
  respond_to :json

  def index
    articles = Article.all
    respond_with articles
  end

  def get
    article = Article.find(params[:id])
    respond_with article
  end

  # etc.
end

You can limit the attributes returned using respond_with article, include: {:id, :title, :description}

Sign up to request clarification or add additional context in comments.

2 Comments

but JSONP requires a callback as Javascript function?
You don't need to use JSONP, Angular $resource expects plain JSON. As long as your controller responds to index, show, create, destroy, and update (or the subset you need), you can use $resource as in your example. Have a look at Angular documentation for $resource, especially the examples. In general, if you create a scaffold in rails, it should work out of the box with Angular. Also, in your example, I would have expected $scope.some_item = $scope.simple.get(); to take an argument (it will be routed to show in your controller).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.