RailsCasts - Ruby on Rails Screencasts

RailsCasts Pro episodes are now free!

Learn more or hide this

AngularJS

#405 AngularJS pro

Feb 05, 2013 | 16 minutes | Ajax, Plugins, APIs
AngularJS is an awesome framework for easily creating rich, client-side applications. Its powerful bindings allow you to do a lot with very little code. Here I show how to integrate Angular with a Rails app.
Click to Play Video ▶
Tweet
  • Download:
  • source code Project Files in Zip (35.4 KB)
  • mp4 Full Size H.264 Video (33.3 MB)
  • m4v Smaller H.264 Video (17.9 MB)
  • webm Full Size VP8 Video (22.8 MB)
  • ogv Full Size Theora Video (40.1 MB)
Browse_code Browse Source Code

Resources

terminal
rails new raffler
cd raffler
rails g controller raffle index
rm public/index.html
rails g resource entry name winner:boolean
rake db:migrate
rake db:seed
Gemfile
group :assets do
 gem 'angularjs-rails'
end
app/assets/javascripts/application.js
//= require angular
//= require angular-resource
views/layouts/application.html.erb
<html ng-app="Raffler">
views/raffle/index.html.erb
<h1>Raffler</h1>
<div ng-controller="RaffleCtrl">
 <form ng-submit="addEntry()">
 <input type="text" ng-model="newEntry.name">
 <input type="submit" value="Add">
 </form>
 <ul>
 <li ng-repeat="entry in entries">
 {{entry.name}}
 <span ng-show="entry.winner" ng-class="{highlight: entry == lastWinner}" class="winner">WINNER</span>
 </li>
 </ul>
 
 <button ng-click="drawWinner()">Draw Winner</button>
</div>
app/assets/javascripts/raffle.js.coffee
app = angular.module("Raffler", ["ngResource"])
app.factory "Entry", ["$resource", ($resource) ->
 $resource("/entries/:id", {id: "@id"}, {update: {method: "PUT"}})
]
@RaffleCtrl = ["$scope", "Entry", ($scope, Entry) ->
 $scope.entries = Entry.query()
 
 $scope.addEntry = ->
 entry = Entry.save($scope.newEntry)
 $scope.entries.push(entry)
 $scope.newEntry = {}
 
 $scope.drawWinner = ->
 pool = []
 angular.forEach $scope.entries, (entry) ->
 pool.push(entry) if !entry.winner
 if pool.length > 0
 entry = pool[Math.floor(Math.random()*pool.length)]
 entry.winner = true
 entry.$update()
 $scope.lastWinner = entry
]
config/environments/production.rb
config.assets.js_compressor = Sprockets::LazyCompressor.new { Uglifier.new(mangle: false) }
controllers/entries_controller.rb
class EntriesController < ApplicationController
 respond_to :json
 def index
 respond_with Entry.all
 end
 def show
 respond_with Entry.find(params[:id])
 end
 def create
 respond_with Entry.create(params[:entry])
 end
 def update
 respond_with Entry.update(params[:id], params[:entry])
 end
 def destroy
 respond_with Entry.destroy(params[:id])
 end
end
loading

AltStyle によって変換されたページ (->オリジナル) /