魔術師見習いのノート

プロフィール

魔術師見習い
Author魔術師見習い-_-.
Twitter魔術師見習い

コンピュータ関係のメモを主に書きます.

MENU

AngularJS1.5 メモ(1) 基本的な記載方法

投稿日:
タグ:

本稿はAngularJS1.5系の基本的な記載方法のサンプル集である。

コンポーネント化する場合
<!doctype html>
<html ng-app="sampleApp">
<head>
<meta charset="UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<script>
var app = angular.module("sampleApp", []);

app.component("sample", {
  template: '<div>hello</div>',
  controller: function() {},
  bindings: {}
});
</script>
<title>sample</title>
</head>
<body>
<sample></sample>
</body>
</html>
templateの代わりに、templateUrlを使用することで、テンプレートを別のファイルに記載することもできる。
パラメータを使用する場合
controllerAsで名前を指定すると、その名前でメンバを指定できる。
AngularJSのng-〜属性以外で、メンバの参照を行う場合、「{{〜}}」で囲う。
<!doctype html>
<html ng-app="sampleApp">
<head>
<meta charset="UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<script>
var app = angular.module("sampleApp", []);

app.component('sample', {
  template: '<div>hello, {{sample.value}}</div>',
  controller: function(){},
  controllerAs: 'sample',
  bindings: {
    value: '@'
  }
});
</script>
<title>sample</title>
</head>
<body>
<sample value="world"></sample>
</body>
</html>
バインディングの種類は以下の通りである。
バインディング説明
@文字列と連携。評価しない。
&メソッド連携。
<オブジェクト連携。単方向データバインディング
=オブジェクト連携。双方向データバインディング
メソッド定義
コントローラ内でメンバを指定する場合、thisを使って指定する。
<!doctype html>
<html ng-app="sampleApp">
<head>
<meta charset="UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<script>
ctrlFunc = function() {
  this.value = 'button';
  this.func = function(){
    this.value = 'pushed';
  }
};
var app = angular.module("sampleApp", []);

app.component('sample', {
  controller: ctrlFunc,
  controllerAs: 'sample',
  template: '<div>hello, {{sample.value}}</div><input type="button" value="button" ng-click="sample.func();">'
});
</script>
<title>sample</title>
</head>
<body>
<sample></sample>
</body>
</html>
サービスを使用する場合
以下は$windowサービスを使用したサンプル。
<!doctype html>
<html ng-app="sampleApp">
<head>
<meta charset="UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<script>
ctrlFunc = function($window) {
  this.func = function(){
    $window.alert("warn");
  }
};
var app = angular.module("sampleApp", []);

app.component('sample', {
  controller: ctrlFunc,
  controllerAs: 'sample',
  template: '<input type="button" value="button" ng-click="sample.func();">'
});
</script>
<title>sample</title>
</head>
<body>
<sample></sample>
</body>
</html>
モジュールを使用する場合
追加モジュールを使用する場合、パッケージ管理にbowerというJavaScriptのパッケージ管理を使用すると便利である。
以下はhtmlをバインドする例。
<!doctype html>
<html ng-app="sampleApp">
<head>
<meta charset="UTF-8">
<script src="bower_components/angular/angular.min.js"></script>
<script src="bower_components/angular-sanitize/angular-sanitize.min.js"></script>
<script>
ctrlFunc = function() {
  this.content = '<div>hogehoge</div>';
};

var app = angular.module("sampleApp", ['ngSanitize']);

app.component('sample', {
  controller: ctrlFunc,
  bindings: {},
  controllerAs: 'sample',
  template: '<div ng-bind-html="sample.content"></div>'
  });
</script>
<title>sample</title>
</head>
<body>
<sample></sample>
</body>
</html>
計算する場合
<!doctype html>
<html ng-app="sampleApp">
<head>
<meta charset="UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<script>
var app = angular.module("sampleApp", []);

app.component("sample", {
  template: '<div>{{1 + 3}}</div>',
  controller: function() {},
  bindings: {}
});
</script>
<title>sample</title>
</head>
<body>
<sample></sample>
</body>
</html>
コーディングレスのデータバインディング
<!doctype html>
<html ng-app="sampleApp">
<head>
<meta charset="UTF-8">
<script
src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<script>
var app = angular.module("sampleApp", []);

app.component("sample", {
  template: '<input type="text" ng-model="sample.text"><div>text: {{sample.text}}</div>',
  controllerAs: "sample",
  controller: function() {
    this.text = "hoge";
  },
  bindings: {}
});
</script>
<title>sample</title>
</head>
<body>
<sample></sample>
</body>
</html>

Appendix

bower

bowerとはフロントエンド(クライアントサイドJavaScript)用パッケージマネージャである。

bowerは以下のようにしてインストールできる。

  1. npmをインストール。
    user% aptitude install npm
  2. bowerをインストール。
    user% npm install bower -g

npmとはNode Package Managerの略で、Node.js(サーバーサイドJavaScript)用のパッケージ管理ツールのこと。
理由は不明だが、bowerはnpm経由でインストールできる。

bowerの使用例を以下に簡単に記す。
user% bower search キーワード
検索
user% bower install ソース
user% bower install ソース#バージョン
インストール
トラブルシューティング

以下、正常にできなかった場合にありそうなミス。

  • AngularJSを取り込むscriptタグの閉じタグが抜けていた。
  • ;または)などの終端を表す記号が漏れていた。

AngularJS1.5 メモ(2)

投稿日:
タグ:

AngularJS1.5のメモ。

サービス

$window
メソッド説明
$window.alert(メッセージ)警告
$window.confirm(メッセージ)確認
$window.prompt(メッセージ)テキスト入力

$http

HTTPクライアントやajax通信を行う方法の1つに$httpサービスを使用する方法がある。
以下、そのサンプルである。

<!doctype html>
<html ng-app="sampleApp">
<head>
<meta charset="UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<script>
var app = angular.module("sampleApp", []);

function ctrlFunc($http, $window) {

  this.func = function(){

    $http.post('http://localhost:8090',{data:{value1:'hoge', value2:2}})
    .success(function(data, status, headers, config){
      $window.confirm("success");
    })
    .error(function(data, status, headers, config){
      $window.alert("error");
    });
  };

}

app.component("sample", {
    template: '<input type="button" value="button" ng-click="sample.func();" >',
    controllerAs: "sample",
    controller: ctrlFunc,
    bindings: {}
  });
</script>
<title>sample</title>
</head>
<body>
<sample></sample>
</body>
</html>
$httpサービスのショートカットメソッド
HTTPメソッドメソッド備考
GET$http.get(url, config)
POST$http.post(url, config)
PUT$http.put(url, config)
PATCH$http.patch(url, config)
DELETE$http.delete(url, config)
HEAD$http.head(url, config)
$http.jsonp(url, config)JSONPでリクエスト
$http(config)のパラメータ
パラメータ名備考
methodメソッド
urlURL
paramsクエリ情報
dataリクエスト本体のデータ
headersリクエストヘッダ
timeoutタイムアウト時間
responseTypeレスポンスの型
cacheHTTP GETリクエストをキャッシュするか
xsrfHeaderNameCSRFトークンで利用するリクエストヘッダ名
xsrfCookieNameCSRFトークンを含んだクッキー名
paramSerializerクエリ情報のシリアライズ方法
transformRquestリクエスト変換関数
transformResponseレスポンス変換関数
withCredentialsクロスドメイン(オリジン)のアクセスを許可するか
$http(config)のコールバック設定
メソッド備考
success(成功時のメソッド)
error(失敗時のメソッド)
then(成功時のメソッド, 失敗時のメソッド)

$resource(URL, デフォルトパラメータ, 追加情報, 動作オプション) ※第1引数以外全て任意

クライアントがREST(というかCRUDな)設計の場合、$httpを使用せずに$resourceで簡単に記載することができることがある。
以下、サンプルである。

  • <!doctype html>
    <html ng-app="sampleApp">
    <head>
    <meta charset="UTF-8">
    <script src="bower_components/angular/angular.min.js"></script>
    <script src="bower_components/angular-resource/angular-resource.min.js"></script>
    <script>
    var app = angular.module("sampleApp", ['ngResource']);
    
    function ctrlFunc($resource, $window) {
      function success(){window.confirm("success");}
      function fail(){window.alert("fail");}
      this.func = function(){
        var hoge = $resource('http://localhost:8090/hoge/');
        var val = hoge.query({}, success, fail);
      };
    }
    
    app.component("sample", {
      template: '<input type="button" value="button" ng-click="sample.func();" >',
      controllerAs: 'sample',
      controller: ctrlFunc,
      bindings: {}
      });
    </script>
    <title>sample</title>
    </head>
    <body>
    <sample></sample>
    </body>
    </html>
  • 
    
func(パラメータ, 成功時のメソッド, 失敗時のメソッド) ※引数は全て任意
HTTPメソッドメソッド備考
GETquery{method:'GET', isArray:true}全取得
GETget{method:'GET'}単一取得
POSTsave{method: 'POST'}新規データ登録
DELETEremove{method: 'DELETE'}既存データ削除
delete
追加情報
メソッド説明

一覧