LoginSignup
26
26

More than 5 years have passed since last update.

AngularJSで動的生成したselectタグに初期値を設定する

Posted at

ダメパターン

<html ng-app="mine">
  <head>
    <script src="angular.min.js"></script>
    <script src="sample.js"></script>
  </head>
  <body>
    <select ng-model="point">
      <!-- ng-repeat を使って option タグを動的に生成している -->
      <option ng-repeat="value in values" value="{{value}}">{{value | number:1}} pt</option>
    </select>
  </body>
</html>
sample.js
angular
.module('mine', [])
.run(function($rootScope) {

    var values = [];

    for (var i=0; i<=1; i+=0.1) {
        values.push(i);
    }

    $rootScope.values = values;

    $rootScope.point = 0.5; // 0.5 を初期選択状態にしているつもり
});

表示結果

angularjs.JPG

0.5 が初期選択されない。

OKパターン

<html ng-app="mine">
  <head>
    <script src="angular.min.js"></script>
    <script src="sample.js"></script>
  </head>
  <body>
    <select ng-model="point"
            ng-options="value as (value | number:1) + ' pt' for value in values"></select>
  </body>
</html>

sample.js は変更なし。

表示結果

angularjs.JPG

0.5 が初期選択されている。

つまり

select タグを動的に生成する場合は、 ng-options を使う。

やや独特の記法なので、 API ドキュメント をしっかり読む必要がある。

26
26
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
26
26