バインディング
AngularJSのバインディングの種類は色々ありますが
今回は"="などと比べて理解しにくい"?"と"&"について書いてみたいと思います。
?について
私はバインディングに"?"のという記号が存在するのを半年以上も知りませんでした笑
実際にどのような働きをするかというと、"?"があるとコンポーネントの読み込みが終わった後にバインディングをしてくれます。
以下のコードは"?"が付いている時と付いていない時の挙動が分かるように書いています。
questionController.html
<question-component param1="'hogehoge'" param2="'hogehoge'"></question-component>
questionComponent.js
angular.module('myApp')
.component('questionComponent', questionComponent);
class questionComponentClass {
constructor() {
this.param1 = "fugafuga" //この2行で値を変更している
this.param2 = "fugafuga"
}
}
questionComponentClass.$inject = [];
var questionComponent = {
controller: questionComponentClass,
templateUrl: 'component/questionComponent.html',
binding: {
param1: '<',
param2: '<?' //こちらは?がついている
}
}
questionComponent.html
?が付いていないと{{$ctrl.param1}}になります。
?が付いていると{{$ctrl.param2}}になります。
実際に実行すると以下のように表示されます。
?が付いていないとhogehogeになります。
?が付いているとfugafugaになります。
&について
次に"&"について書いてみます。バインディングを"&"にするとそのバインディングは関数として扱われます。
以下のコードはバインディングが"&"の時の書き方です。
andComponentClass.js
angular.module('myApp')
.component('andComponent', andComponent);
class andComponentClass {
constructor() {}
and(value) {
andFunction({value: result}); //オブジェクトで定義
}
}
andComponentClass.$inject = [];
var andComponent = {
controller: andComponentClass,
templateUrl: 'component/andComponentClass.html',
binding: {
andFunction: '&'
}
}
andController.html
<and-component and-function="$ctrl.smple(value)"></and-component> //引数にキー名を記入
ポイントなのはandController.html内で呼び出すときにバインディング名=andController.html内の関数(キー名)
になる事とコンポーネントでは一度ラップしてバインディングを呼ぶ点です。
他のバインディングと違い、かなりクセが強いので理解するのが難しいですが、呼び出す時を意識すれば
扱えるようになると思います。