「Ruby on Rails Tutorial」のサンプルアプリをAngularJSとBootstrap3を使う形にして作成します。前回、サーバーで定義したユーザー情報をAngularJSの$resourceサービスを使って取得して、表示できるようにしました。今回は、そのresourceサービスのアクションをfactoryメソッドを使ってサービスとして定義します。
1)AngularJSの$resourceのRESTアクションをサービスとして定義
Railsのサーバー側にAngularJSの$resourceサービスを使ってアクセスするアクションをサービスとして定義します。
myModule = angular.module('myModule', ['ui.bootstrap','ngRoute','ngResource']);
myModule.factory("userResource", function($resource) {
return $resource("/app/users/:id", { id: "@id" },
{
'create': { method: 'POST' },
'index': { method: 'GET', isArray: true },
'show': { method: 'GET', isArray: false },
'update': { method: 'PUT' },
'destroy': { method: 'DELETE' }
}
);
});
2)各AngularJSのコントローラを修整
前回作成したuser一覧をサーバーから取得するAngularJSコントローラを上記で定義したサービスを使う形に変更します。
(修整前)
myModule.controller("UsersIndexCtrl", function($scope,$resource) {
var rtn = $resource('/app/users');
$scope.users = rtn.query();
});
(修整後)
myModule.controller("UsersIndexCtrl", function($scope,userResource) {
$scope.users = userResource.index()
});