AngularJS入門09
- 2017年01月23日
- CATEGORY- 1. 技術力{技術情報}
AngularJSとは
AngularJSとはGoogleとコミュニティにより開発されたJavaScript(MVW *1)フレームワークです。
データバインディング、DI(依存注入)などの機能を保有し、複雑なアプリケーションもシンプルに実装可能です。
*1 「MVW」とは「Model View Whatever」の略で、「Model」「View」「その他何でも」という意味です。
今回は前回に引き続き「2. Angular2へのマイグレーションを見越しての、$scope除外(コントローラーのクラス化)」をご紹介します。
実装方法 – Sample03
まずは[sample03.coffee]の実装です。
[sample02.coffee]は[sample03.html]ページ用のJavaScriptです。
以下、全体のソースコードです。
始めにコントローラークラス(‘Sample03Controller’)を作成します。
クラスの作りはシンプルで、コンストラクタで変数(‘title’,’model’)を作成して、’title’に’Sample02’を
‘model.list’に商品リスト(ArrayList)を’model.tax’に税率をそれぞれ設定しています。
class Sample03Controller constructor: () -> @title = 'Sample03' // タイトル @model = list: [ // 商品リスト {code: 100, name: 'おにぎり(梅)', price: 120} {code: 101, name: 'おにぎり(鮭)', price: 150} {code: 200, name: '味噌汁', price: 100} {code: 300, name: 'のり弁', price: 380} {code: 301, name: '幕の内弁当', price: 500} {code: 302, name: 'うな重', price: 1000} ] tax: 1.08 // 税率
次にモジュール(‘mainApp’)を作成し、上で作成したコントローラークラスをAngularのコントローラーとして登録します。
angular .module 'mainApp' .controller 'Sample03Controller', Sample03Controller
続いてHTML部のソースコードの解説です。
‘h3 tag’にmodel(‘s03.title’)を結合(‘ng-bind’)します。
下記でバインドされている、’s03’はコントローラー(‘Sample03Controller’)の別名です。
<h3 ng-bind="s03.title"></h3>
# コントローラーは別名で指定されているので注意が必要です。
設定は前回のルーティング設定で行います。(前回のソースコードより抜粋)
.when '/sample03', { templateUrl: 'samples/sample03.html', controller: 'Sample03Controller', controllerAs: 's03' }
ng-repeatを使いtableとAngular modelを結合します。
1. ng-repeatを使いmodel(s03.model.list)を1レコードずつ変数(item)に格納します。
2. Code列(tr)とmodel(item.code)を結合(ng-bind)します。
3. 商品名称列(tr)とmodel(item.name)を結合(ng-bind)します。
4. 価格(tr)とmodel(item.price)を結合(ng-bind)します。
5. 税込(tr)とmodel(item.price * s03.model.tax | number 0)を結合(ng-bind)します。
* ここでは価格 ✖ 税率を計算し、その結果にフィルター(number)を適応して小数点以下を四捨五入しています。
<tbody md-body> <tr md-row md-select="dessert" ng-repeat="item in s03.model.list"><!-- 1 --> <td md-cell ng-bind="item.code"></td><!-- 2 --> <td md-cell ng-bind="item.name"></td><!-- 3 --> <td md-cell ng-bind="item.price"></td><!-- 4 --> <td md-cell ng-bind="item.price * s03.model.tax | number:0"></td><!-- 5 --> </tr> </tbody>
最後にmodel(‘s03.model.tax’)とinput tagを結合(‘ng-bind’) します。
ここでは税率の変更を行います。変更された税率は即座に適応され、税込価格がリアルタイムで変更されます。
<input ng-model="s03.model.tax">
ソースコード
ソースコードは以下のリポジトリよりチェックアウトできます
https://github.com/Sin330/ng_sample
デモ
下記のサイトから今回紹介したサンプルが実行できます。
https://ng-smple.appspot.com/
次回より「Tips形式」でをAnguarをご紹介します。
【関連記事】
Google App Engine 第一回
Google App Engine 第二回
Javaのライブラリを手軽にテストしたい!! Groovy入門 第1回
Google App Engine 第三回
Google App Engine 第四回
Google App Engine 第五回
Google App Engine 第六回
Google App Engine 第七回
Google App Engine 第八回
Google App Engine 第九回
Google App Engine 第十回
Google App Engine 第十一回
Google App Engine 第十二回
AngularJS入門01
AngularJS入門02
AngularJS入門03
AngularJS入門04
AngularJS入門05
AngularJS入門06
AngularJS入門07
AngularJS入門08
- 2017年01月23日
- CATEGORY- 1. 技術力{技術情報}