LoginSignup
19
20

More than 5 years have passed since last update.

AngularJSでselect要素のデータバインド

Posted at

AngularJSでselect要素を利用するTipsです。

controller.js
$scope.colors = [
    {name:'black', shade:'dark'},
    {name:'white', shade:'light'},
    {name:'red', shade:'dark'},
    {name:'blue', shade:'dark'},
    {name:'yellow', shade:'light'}
];
$scope.color = $scope.colors[2]; //←注目!
template.html
<select ng-model="color" ng-options="c.name for c in colors"></select>

上記が簡単なselect要素のデータバインドになります。

template.htmlのng-modelは、このselect要素をスコープで紐付けるために
使用するので、他のスコープ変数とは被らないようにしましょう。

ng-optionsの中身は、
ラベル for 配列の値 in 配列
という指定になります。
optionsのvalueには自動的に配列のキー値が入ります。

ここでの注目はcontroller.js内の"注目!"と書かれた部分。
これは デフォルトで"selected"を適用する箇所 を指定しています。

サンプルだと、model="color"のselectedはcolors[2]の要素に
適用するという事になります。
言葉だとわかりづらいので、一度お試しください。便利です。

サンプルでは配列形式の適用ですが、オブジェクト形式でも適用が可能です。

今回は解説しませんが、グループ指定等も簡単にできますので、
興味がある方は↓詳しい解説の公式リファレンスをご覧ください

詳しい解説

http://docs.angularjs.org/api/ng/directive/select
↑公式リファレンス

http://js.studio-kingdom.com/angularjs/ng_directive/select
↑日本語リファレンス

19
20
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
19
20