***サンプル [#gb08de87]
$resourceを使ったサンプルです。というかまだ殴り書きメモ。

RESTの仕様は[[$httpのときのサンプル>AngularJS/TIPS集/$http]]とおなじく、
 /api/hoge/ にHTTP GETすると一覧(JSON配列)
 /api/hoge/[id].json にGETすると詳細
 /api/hoge/ にHTTP POST すると登録
こんなよくある仕様だとします。これらに対して、[[$httpのときのサンプル>AngularJS/TIPS集/$http]] のときのようにサービスを定義しますが、$resourceはあらかじめ定義済みのメソッドがあり、それをそのまま利用するとして

 hogeService.query();
 hogeService.get(data);
 hogeService.save(postData);
こんな感じでサービスを呼び出せるようにします。

***サービスの定義 [#i3b1c894]

 angular.module(APP_NAME)
     .factory('hogeService', ['$resource', function ($resource) {
         // Public API here
         return $resource('/api/hoge/:key.:ext',
             {
             },
             {
             })
     }]);
 

***コントローラからの呼び出し方 [#tf7e9d0f]


 angular.module(APP_NAME)
     .controller('PasswordCtrl', ['hogeService', '$scope', function (hogeService, $scope) {
          // $resourceのサンプル
         $scope.hoges = hogeService.query();
 
         $scope.addRow = function () {
             $scope.hoges.push($scope.postData);
             hogeService.save($scope.postData);
         };
 
         $scope.delete = function (id) {
             console.log(id);
             var result = hogeService.get({key: id, ext: 'json'},
                 function () {
                     alert(result.key);
                 });
         };
 
 
     }
     ])
 ;

トップ   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS