トッカンソフトウェア

AngularJS Controller

今回はコントローラをやります。コントローラは、画面表示、ボタン押下、テキスト入力など画面動作と連動して呼び出される
JavaScriptのオブジェクトになります。


単純なコントローラ

				

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>AngularJS Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<!-- script src="angular.min.js"></script -->
<script>

var testApp = angular.module("testApp", []);

function TestCtrl() {
	this.message = "Hello World!!";
}

testApp.component("hello", {
	template: "<h1>" + "{{obj.message}}" + "</h1>",
	controller: TestCtrl,
	controllerAs: "obj"
});

</script>
</head>
<body ng-app="testApp">
	<hello></hello>
</body>
</html>


			
上記のサンプルプログラムを実行すると以下のようなソースに変換されます(bodyのみ抜き出し)。
				
<body ng-app="testApp" class="ng-scope">
	<hello class="ng-isolate-scope">
		<h1 class="ng-binding">Hello World!!</h1>
	</hello>
</body>


			


controller、controllerAs

controller属性でオブジェクトの元となるメソッド、またはクラスを指定します。
生成されたオブジェクトは、controllerAs属性で指定した名前のオブジェクトになります。

サンプルではメソッドまたはクラス指定でTestCtrlを指定し、それで作成されたオブジェクトの名称は"obj"になります。
				
testApp.component("hello", {
	template: "<h1>" + "{{obj.message}}" + "</h1>",
	controller: TestCtrl,
	controllerAs: "obj"
});


			
controllerAsを省略すると、オブジェクト名は"$ctrl"になります。
上記のサンプルは、以下のようになります。
				
testApp.component("hello", {
	template: "<h1>" + "{{$ctrl.message}}" + "</h1>",
	controller: TestCtrl
});


			
$ctrlの頭に$(ドルマーク)がついていますが、AngularJSが提供するオブジェクトなどに付きます。
JQueryみたいに特別な動作をするのではなく、ただの変数名なので、自分で作成するオブジェクトにも付けられますが、
AngularJSと名称が重複する可能性があるので付けない方がいいです。

式(Expressions)、ng-bind属性

コントローラのオブジェクトをHTMLに表示するとき{{式}}を使用します。ここにはJavaScriptのような記述ができます。
				
{{$ctrl.message}} → $ctrlオブジェクトのmessage属性を表示
{{1 + 1}}     → 2を表示


			
ng-bind属性を使用すると同じことができます。サンプルは以下のように変更できます。
				
testApp.component("hello", {
	template: "<h1 ng-bind='obj.message'></h1>",
	controller: TestCtrl,
	controllerAs: "obj"
});


			

ボタンとテキストの連携

コントローラにボタンとテキストを連携させてみます。
				
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>AngularJS Test</title>
<!-- script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script -->
<script src="angular.min.js"></script>
<script>

var testApp = angular.module("testApp", []);

function TestCtrl() {
	this.message = "Hello World!!";
	this.clearClick = function(){
		this.message = "";
	}
}

testApp.component("hello", {
	template: "<input type='text' ng-model='obj.message' />" +
		"<input type='button' ng-click='obj.clearClick()' value='clear' />" +
		"<h1 ng-bind='obj.message'></h1>",
	controller: TestCtrl,
	controllerAs: "obj"
});

</script>
</head>
<body ng-app="testApp">
	<hello></hello>
</body>
</html>


			

ng-model属性、ng-click属性

テキストなどの入力項目とコントローラの属性を連携させるには、ng-model属性を使用します。
ボタンのクリックとコントローラのメソッドを連携させるには、ng-click属性を使用します。


ページのトップへ戻る