AngularJS再入門メモ
2015/07/03
国内では相当disられて下火感を醸しているAngularJS
disるほどこのフレームワークに詳しくないので理解したところをメモ。
Controllerって何するの?
分かったようで分からないController
https://docs.angularjs.org/guide/controller
AngularScopeを初期化するためのコンストラクタである
と、書かれている。
よく分からない。。
- $scopeオブジェクトの初期状態を決定する
- $scopeオブジェクトに振るまいを与える
サーバから取得したデータを表示させたい場合、Controllerはどのように関わってくるのだろうか。
サーバからデータを取得してアプリケーションで使用するエンティティに変換する処理は誰が担当するのだろうか。
そして、そのデータをControllerに対してどのように渡すべきなのか。
$scopeオブジェクトの初期状態を決定する
という文言を真に受けると、Controller内でサーバとの通信を行い、取得したjsonなりをアプリ用に整形して$scope.dataList = (サーバから取ってきて加工したデータ一覧)と割り当てるのだろうか。
この辺の責務がよく分からず混乱している。
ドキュメントを読み進める。
Using Controllers Correctly
In general, a Controller shouldn’t try to do too much. It should contain only the business logic needed for a single view.
The most common way to keep Controllers slim is by encapsulating work that doesn’t belong to controllers into services and then using these services in Controllers via dependency injection. This is discussed in the Dependency Injection Services sections of this guide.
ControllerはあるViewに必要なビジネスロジックのみを担当すべき。
Controllerに属さない処理はサービスに移譲し、ControllerはDIによって定義されたサービスを利用するだけ、という関係にする。
なるほどね。
上で書いた『サーバからjsonなりを取ってきてアプリ用に整形する』はControllerに属した処理とは言えない。
この処理は他のControllerで使うかもしれない。なので、サービスに切り分けてそれをControllerが使うようにする。
ControllerはViewがやるべき処理や保持すべき状態の区画を決めて、必要なものだけを公開する。
Service
Angular services are substitutable objects that are wired together using dependency injection (DI). You can use services to organize and share code across your app.
何を言ってるかよく分からないが、おそらくアプリ内で共有するような処理を担当するオブジェクトなのだろう。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
angular. module('myServiceModule', []). controller('MyController', ['$scope','notify', function ($scope, notify) { $scope.callNotify = function(msg) { notify(msg); }; }]). factory('notify', ['$window', function(win) { var msgs = []; return function(msg) { msgs.push(msg); if (msgs.length == 3) { win.alert(msgs.join("\n")); msgs = []; } }; }]); |
サービスを定義するにはfactoryというメソッドを呼ぶみたい。
上のコードではnotifyというサービスを作っている。
中はクロージャー(?)で、呼ばれるたびに受け取ったmsgを配列に格納、配列の長さが3になったタイミングでアラートを表示する、という感じ。
$windowをサービス内で使うことが良いかどうかは謎だが。
コントローラー側のDI宣言部分でnotifyと表記することでコントローラー内でnotifyの処理を呼び出すことができる。
このコントローラーはcallNotifyというAPIのみを公開している。