2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AngularJSのBinding(?,&)の使い方について書いてみた

Last updated at Posted at 2017-08-31

バインディング

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内の関数(キー名)
になる事とコンポーネントでは一度ラップしてバインディングを呼ぶ点です。

他のバインディングと違い、かなりクセが強いので理解するのが難しいですが、呼び出す時を意識すれば
扱えるようになると思います。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?