LoginSignup
3
0

More than 5 years have passed since last update.

RailsでAngularJSの導入と動作確認(基礎編)

Last updated at Posted at 2016-04-06

AngularJSの導入

AngularJS - 公式ページからAngularJSの本体のファイル(angular.min.js)を取得し、vendor/assets/javascripts/ に配置する。

curl https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js > vendor/assets/javascripts/angular.min.js
curl https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js.map > vendor/assets/javascripts/angular.min.js.map

AngularJSの設定ファイルとなる app.coffee を作成する。

# app/assets/javascripts/app.coffee


app = angular.module('sampleApp', [])

app.config ($httpProvider) ->
  $httpProvider.defaults.headers.common['X-CSRF-Token'] =
    document.getElementsByName("csrf-token")[0].content

$(document).on 'page:load', ->
  $('[ng-app]').each ->
    module = $(this).attr('ng-app')
    angular.bootstrap(this, [module])

jqueryとturbolinksも一緒に動くようにするために、jquery-turbolinksを入れる。

# Gemfile
gem 'jquery-turbolinks'

jquery.turbolinks、angular.min、appを application.js に追記する。
(Railsが記載したjsファイルを読み込むようになる。)

# app/assets/javascripts/application.js
//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require turbolinks
//= require angular.min
//= require app
//= require_tree .

application.html.erbにng-appディレクティブを追加。
(ng-appディレクティブ内がAngularJSにより解析されるので、その中でAngularJSが使えるようになる。)

# app/views/layouts/application.html.erb
<!-- app.coffee の戦闘のangular.moduleで宣言した名前にする -->
<html ng-app="sampleApp">

...

Railsはproducton環境の場合、アセットをコンパイルすることによりAngularJSが動かなくなってしまう。そのため、production.rbにconfig.assets.js_compressor = Uglifier.new(mangle: false)を追加しておく。

# config/developments/production.rb

# Compress JavaScripts and CSS.
# config.assets.js_compressor = :uglifier
config.assets.js_compressor = Uglifier.new(mangle: false)
# config.assets.css_compressor = :sass

動作確認

では、動作確認のために、コントローラーを作成する。

rails g controller Templates index --skip-assets

次のように記載。テキストフィールドにng-modelでnameを定義し、それを、{{name}}でデータバインティングして動的に表示するようにしている。

# app/views/templates/index.html.erb
<h1>Templates#index</h1>

<div>
  <%= label_tag :naem, "名前" %>
  <%= text_field_tag :name, "", "ng-model" => "name" %>
</div>

<p>こんにちは、「{{name}}」さん。</p>

テキストフィールドに値をいれると、{{}}で囲んだ箇所が動的に変化することがわかる。もし、うまく動かない場合は、JavaScriptコンソール(Chromeの場合)を開きエラーが発生していないか確認する。

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0