Hello AngularJS

rails で angularjs 入門するためにちょっとメモ

基本的に下記のGMOメディア エンジニアブログさんで紹介されている方法そのままなので、見てない方は是非そちらを読んでください。

http://tech.gmo-media.jp/post/70940891525/angularjs-on-rails

前提として

  • railsの構築環境(rbenv,bundler,各種データベースなど)がインストールされている
  • ところどころはしょってるのでrailsの知識必須

スタート

railsプロジェクトを作成する用のGemfileを作成

cat << EOS > Gemfile
source "http://rubygems.org"
gem "rails", "3.2.17"
EOS

bundle インストール

bundle install --path vendor/bundle

angularjs用のプロジェクトを作成

bundle exec rails new example --skip-bundle

いらないファイルを削除

rm -f Gemfile*
rm -rf .bundle
rm -rf vendor/bundle

作ったプロジェクトに移動してGemfileを編集

cd example
# Gemfileを編集
gem "angular-gem", '~> 1.2.1'
gem "mysql2"
...

bundle install --path vendor/bundle
bundle exec rails g angular:install
bundle exec rails s

config/database.yml を適宜編集

http://localhost:3000/ でチェック

ビューを作成

./public/test.hml に以下を貼り付け
<!DOCTYPE HTML>
<html ng-app>
<head>
<script src="assets/application.js"></script>
</head>
<body>
<div>
<label>Name:</label>
<input type="text" ng-model="yourName" placeholder="Enter a name here">
<br/>
<font size="4">Hello {{yourName}}!</font>
</div>
</body>
</html>

http://localhost:3000/test.html
を確認してフォームに適当な文字列を打つとちゃんと動いていればangularjsは動いているので次

ここからは簡易的なAPIを作ってangularjsと連携させます

モデル作成

bundle exec rails g model article title description
bundle exec rake db:create
bundle exec rake db:migrate

データを作成

// ./db/seed.rb
1.upto(20) do |num|
Article.create(:title => "title#{num}", :description => "description#{num}")
end
bundle exec rake db:seed

コントローラー作成

bundle exec rails g controller articles index

// ./app/controller/articles_controller.rb
def index
@articles = Article.all
render json: @articles
end

もっかい
bundle exec rails s

http://localhost:3000/articles/index
にアクセスしてみる

それっぽいデータがでてれば次

モジュールを作成

# ./app/assets/javascripts/app.js.coffee
window.App = angular.module('ArticleSample', ['ngResource'])

サービス(モデル)を作成

# ./app/assets/javascripts/angular/services/articles.js.coffee
App.factory 'Articles', ['$resource', ($resource) ->
$resource '/articles/index'
]

コントローラーを作成

# ./app/assets/javascripts/angular/controllers/articles_ctrl.js.coffee
App.controller 'ArticlesCtrl', ['$scope', 'Articles', ($scope, Articles) ->
$scope.articles = Articles.query()
]

読み込むjsを変更. jqueryとかいらないので削除

# ./app/assets/javascripts/application.js
//= require angular
//= require angular-resource
//= require app
//= require_tree ./angular

ビューを作成

# ./public/test.html
<!DOCTYPE HTML>
<html ng-app="ArticleSample">
<head>
<script src="assets/application.js"></script>
</head>
<body>
<div>
<label>Name:</label>
<input type="text" ng-model="yourName" placeholder="Enter a name here">
<br/>
<font size="4">Hello {{yourName}}!</font>
</div>
<div ng-controller="ArticlesCtrl">
<div ng-repeat="article in articles">
<p>{{article.title}}:{{article.description}}</p>
</div>
</div>
</body>
</html>

http://localhost:3000/test.html
にアクセス

/articles/index のAPIのデータ(titleとdescription)が表示されていればOK

angularjs というか rails 難しい