AngularJSとRails4でRestアプリ作成(2)AngularJSのルート、テンプレートの設定

1)AngularJSのrouteサービスを導入
 
①angular-routeをインクルード
 
$ vi app/assets/javascripts/application.js
 
//= require angular-route
 
②ngRouteを依存性の設定に追加
 
$ vi app/assets/javascripts/mymodule.js
 
var mymodule = angular.module(“myModule”, [‘ngRoute’]);
 
2)ルートプロバイダ、パーシャルテンプレートの設定
 
ファイル内でRailsのヘルパーを使用するため、ファイルの拡張子に.erbを追加しています。
$ vi app/assets/javascripts/mymodule.js.erb

var mymodule = angular.module("myModule", ['ngRoute']);

mymodule.config(function($routeProvider) {
  $routeProvider
    .when("/users/dummy", {
      templateUrl: "<%= asset_path('users/dummy.html') %>",
      controller: "UsersDummyCtrl" })
    .otherwise({
      templateUrl: "<%= asset_path('users/index.html') %>",
      controller: "UsersIndexCtrl" });
});

 
3)インデックスのコントローラファイル作成
 
上記でAngularJSのルート設定を行い、各ルート毎にパーシャルテンプレートとコントローラを定義する形に変更したので、インデックス用のコントローラを定義します。
 
$ vi app/assets/javascripts/mymodule.js.erb

mymodule.controller("UsersIndexCtrl", function($scope) {
  $scope.users = [
    {
      name: "相川 一郎",
      email: "aikawa@example.com"
    },
    {
      name: "石井 二郎",
      email: "ishii@example.com"
    },
  ]
});

 
4)パーシャルテンプレートファイルを作成
 
①indexのパーシャルテンプレートを作成
 
今までapp/views/users/index.html.erbに記述していた内容をパーシャルテンプレートファイルに記述します。
 
動作確認のためダミーページへのリンクを追加しています。
 
$ vi app/assets/templates/users/index.html

<div ng-controller="UsersIndexCtrl">
  <h3>ユーザー一覧</h3>

  <table class="table table-bordered">
    <thead>
      <td>名前</td>
      <td>メールアドレス</td>
    </thead>
    <tbody>
      <tr ng-repeat="user in users">
        <td>
          {_{user.name}}
        </td>
        <td>
          {_{user.email}}
        </td>
      </tr>
    </tbody>
  </table>
  <a href="#/users/dummy">ダミー</a>
</div>

 
②ダミーページのパーシャルビューを仮作成
 
$ vi app/assets/templates/users/dummy.html
 
<h3>ダミー</h3>
 
5)AngularJSのレイアウトテンプレートファイルを作成
 
Railsのconfig/route.rbでUsersコントローラのindexアクションをrootにしているので、とりあえずこのビューをレイアウトテンプレートファイルとします。
 
$ vi app/views/users/index.html.erb
 
<div ng-view></div>
 
6)動作確認
 
http://localhost:3000/
 
上記URLでインデックスページが表示され、ダミーのリンク押下でダミーページが表示される事を確認します。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です