LoginSignup
2

More than 5 years have passed since last update.

【vte.cx入門】11.AngularJSによるデータリソースの操作

Posted at

今回まで主にjQueryでの開発手順を説明してきましたが、vte.cxは様々なJavaScript用のライブラリで開発できます。

今回はその一つであるAngularJSによるデータリソースの操作について説明したいと思います。

はじめに

この記事はAngularJSでの開発経験があることを前提に書いています。
まだAngularJSで開発を行ったことがない場合は、基礎的なことを学んだ上で読むことをお勧めしています。

AngularJSのajax通信($httpサービス)

AngularJSのajax通信でリソースデータにアクセスできます。
$httpサービスを使用します。

GETリクエスト

GET
$http({
      method: 'GET',
      url: url
}).then(function(res){
   // 取得成功
   // res.data.feed でfeedデータ取得
}, function(res){
   // 取得失敗
});

POSTリクエスト

POST
$http({
      method: 'POST',
      url: url,
      data: JSON.stringify(reqdata)
}).then(function(res){
   // 登録成功
   // res.data.feed でfeedデータ取得
}, function(res){
   // 登録失敗
});

PUTリクエスト

PUT
$http({
      method: 'PUT',
      url: url,
      data: JSON.stringify(reqdata)
}).then(function(res){
   // 更新成功
   // res.data.feed でfeedデータ取得
}, function(res){
   // 更新失敗
});

DELETEリクエスト

GET
$http({
      method: 'DELETE',
      url: url
}).then(function(res){
   // 取得成功
   // res.data.feed でfeedデータ取得
}, function(res){
   // 取得失敗
});

$scopeで双方向データバインディングを行う

\$httpで受け取ったデータを$scopeに定義することで双方向データバインディングを行うことができます。

javascript
$scope.data.feed = {};
$http({
      method: 'GET',
      url: url
}).then(function(res){
   // 取得成功
   // $scopeに格納
   $scope.data.feed = res.data.feed;
}, function(res){
   // 取得失敗
});
html
<div>{{data.feed.entry[0].title}}</div>

ng-modelでリクエストデータを構築する

POSTやPUTをする際に、feed形式のリクエストデータが必要になります。
それをng-modelを使用し構築することで、ソースを簡略化できます。

html
<input type="text" ng-model="entry.title" value="hoge" />
<input type="text" ng-model="entry.subtitle" value="foo" />
<input type="text" ng-model="entry.summary" value="bar" />
javascript
$scope.entry = {};
$scope.data = {};

$scope.data.feed.entry = [];
$scope.data.feed.entry[0] = $scope.entry;

console.log($scope.data.feed.entry[0].title);     ←   hoge
console.log($scope.data.feed.entry[0].subtitle);  ←   foo
console.log($scope.data.feed.entry[0].summary);   ←   bar

こうすることでng-model="entry.title"などの値が変化したとしても、リアルタイムで$scope.data.feed.entryに値が格納されるためHTMLを編集するだけでデータの構築を行うことができます。

終わりに

vte.cxのリソースデータはJSONで扱うため、AngularJSの特徴である双方向データバインディングと非常に相性が良いです。
他のjavascriptフレームワークでもajax通信ができるライブラリであればvte.cxは対応できるはずです。
いろいろなフレームワークでアプリ開発を行ってみてください。

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
2