JS MVC フレームワークでは、他の JS アプリと同様に、オブジェクト/クラス/モデルを定義して操作します。Web サービス (AJAX 呼び出し) からクライアントのリストを取得すると、angularJS は $http または $resource を使用して自動的に JS オブジェクトに変換します (どちらもフレームワークの Web サイトで詳しく説明されています)。ただし、いつでも独自のものを作成し、POST を介してすぐに、または後で DB に追加できます。モデルの新しいインスタンスを追加するために「ビュー」を変更する必要はありません。
これは、私のアプリケーション用に私が持っているコントローラーの例です。ロジックのほとんどは、明確にするために削除され、コメントに置き換えられています。これはエントリを表し、エントリのリストは親コントローラに格納され、コントローラは ng-repeat ディレクティブを介して生成されます (以下の html コードを参照)。
コントローラ:
/**
* Entry Controller
* @class entryCtrl
*/
ucpaTpaApp.controller(
'entryCtrl',
['$scope', 'httpService',
function($scope, httpService) {
/**
* initiate the entry model, with all the required logic
* Called upon the controller's construction
*/
$scope.initEntry = function initEntry(){
if(!$scope.entry){
$scope.newEntry();
}
}
/**
* Set the fields of the entry, stored on the indicator's metadata
* for new entries.
*/
$scope.newEntry = function newEntry(){
$scope.entry = {
status: {
state: 'new',
connection: 'idle'
},
field_values: {},
saved_field_values: {},
title: ""
};
for(var field in $scope.fields){
$scope.entry.field_values[String($scope.fields[field].id)] = '';
}
};
$scope.resetFields = function resetFields(){
// Resets fields to original status (blank if it is new)
};
/**
* Save a new entry, adding it to the list of entries, and attempting
* to save to the server
*/
$scope.addEntry = function addEntry(){
// Add a copy to array, with status 'new',
// and call saveEntry on it
// After that, reset fields
};
$scope.deleteEntry = function deleteEntry(){
// Delete on WS, remove from array on confirmation
};
$scope.saveEntry = function saveEntry(){
// Save to WS, update status on confirmation
};
$scope.initEntry();
}]
);
テンプレート:
<div class="indicator">
<h3>{{indicator.title}} - {{indicator.score}}</h3>
<div
ng-repeat="entry in indicator.entries"
ng-form="{{entry.id}}"
ng-controller="entryCtrl">
<tr-entry>
</tr-entry>
</div>
</div>
<div ng-controller="entryCtrl">
<tr-entry>
</tr-entry>
</div>
ご覧のとおり、エントリのリストは ng-repeat ディレクティブで表示されます (実際のエントリ DOM は独自のディレクティブである tr-entry で作成されます)。次に、追加のエントリ「新しい」エントリがこのリストの最後に作成されます。そのエントリが保存 (追加) されると、そのエントリ モデルが配列にコピーされ、angularJS はそれを保存しようとします。結果は次のとおりです。「新しいエントリ」はそのフィールドを空白に設定し、新しいエントリが ng-repeat リストに表示されます。もちろん、DB に保存されたという確認が受信された場合にのみ、ステータスが「新規」から「保存済み」に変更されます (バックエンドがデータの検証を実行するため、エントリが拒否される場合があります)。