LoginSignup
4
4

More than 5 years have passed since last update.

rails + angularjs + gonを試してみる

Last updated at Posted at 2016-10-29

railsでangularjsを使うと、何かとコード量が増えてしまった面倒臭い。
gonを使ってrailsとangularを繋いだら楽になるんじゃないかと思って試してみた。
画面遷移は全部rails-wayな想定

angularjsとgonのインストール

gem 'angularjs-rails'
gem 'gon'

application.jsの設定
(turbolinkは削除)

application.js

//= #require turbolinks
//= require angular
application.html.erb

  <%= include_gon %>
  <%= stylesheet_link_tag    'application', media: 'all'%>
  <%= javascript_include_tag 'application' %>
  <!--<%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>-->
  <!--<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>-->

controllerとaction:indexを作っておく

rails g controller hoge index

localhost:3000/hogeへアクセスして画面確認
スクリーンショット 2016-10-29 11.33.52.png

angular-gonな設定

appを設定

application.html.erb
<html ng-app="angular-gon">

app.jsを作成

app/assets/javascripts/app.js
'use strict';

angular.module("angular-gon", []);

コントローラとhtml.erbに追加

app/controllers/hoge_controller.rb
def index
    gon.title = "0から1へ!"
    gon.numbers = [1,2,3]
end
app/assets/javascripts/hoge.js
angular.module("angular-gon").controller('HogeIndexCtrl',
  function () {
    $.extend(this, gon);
  });
app/views/hoge/index.html.erb
<div ng-controller="HogeIndexCtrl as $ctrl">
  <h1>{{$ctrl.title}}</h1>
  <p ng-repeat="number in $ctrl.numbers">{{number}}</p>
</div>

で、localhost:3000/hogeを再表示
スクリーンショット 2016-10-29 11.54.58.png

出たー!!どんどんどん

railsのコントローラからangularjsまでスムーズにデータが流れるので、割とサクサクいけるんじゃないですかね??

  • rails g controllerを改修したら、さらに捗りそう
  • controller@angularとerbのng-controllerの辺りを自動生成させる
4
4
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
4
4