Skip to content

Instantly share code, notes, and snippets.

@milesmatthias
Created June 10, 2014 13:52
Show Gist options
  • Save milesmatthias/fb88c9f066f1c3ab7fae to your computer and use it in GitHub Desktop.
Save milesmatthias/fb88c9f066f1c3ab7fae to your computer and use it in GitHub Desktop.
AngularJS with Rails JSONP API
angular.module('app')
.factory('HeadlineService', ['$http',
function($http) {
'use strict';
var BASE_URL = "<%= [App.settings.api_base_url, '/services/headlines'].join %>",
CALLBACK_STRING = "?callback=JSON_CALLBACK";
return {
getHeadlines: function(){
return $http.jsonp(BASE_URL + CALLBACK_STRING)
},
getHeadlineForId: function(id){
return $http.jsonp(BASE_URL + "/" + id + ".json" + CALLBACK_STRING)
}
}
}
]);
<section class="headline_section" ng-controller="HeadlinesCtrl">
<h3>Here are some headlines...</h3>
<div class="headlines">
<ul>
<li ng-repeat="headline in headlines">
<a href="{{ headline.url }}" target="_none">{{ headline.title }}</a>
</li>
<ul>
</div>
<div class="headline">
<a href="{{ single_headline.url }}" target="_none">{{ single_headline.title }}</a>
</div>
</section>
angular.module('app')
.controller('HeadlinesCtrl', ['$scope', 'HeadlineService',
function($scope, HeadlineService) {
'use strict';
HeadlineService.getHeadlines().success(function(data, status, headers, config){
$scope.headlines = data;
HeadlineService.getHeadlineForId(data[0].id).success(function(data){
$scope.single_headline = data;
}).error(function(error, status, headers, config){
alert('something went wrong getting a headline');
});
}).error(function(error, status, headers, config){
alert('something went wrong getting all the headlines');
});
}
]);
class Services::HeadlinesController < ApplicationController
def index
page = (params[:page] || 1).to_i
per = (params[:per] || 5).to_i
offset = (page - 1) * per
@headlines = Headline.where(:disabled => false).offset(offset).limit(per).to_a
render :json => @headlines.to_json, :callback => params[:callback]
end
def show
@headline = Headline.find(params[:id])
if @headline.present?
render :json => @headline.to_json, :callback => params[:callback]
else
render :json => {error: 'no headline found'}.to_json, :callback => params[:callback], :status => 404
end
end
end
# Services
namespace :services, :defaults => { :format => "json" } do
resources :headlines, only: [:index, :show]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment