AngularJSのドロップダウン

AngularJSは、配列やオブジェクト内のアイテムに基づいてドロップダウンリストを作成することができます。

ng-optionsを使用してドロップダウンを作成する

AngularJSでオブジェクトや配列に基づいてドロップダウンリストを作成したい場合は、 ng-options 指示:

<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="selectedName" ng-options="x for x in names">
</select>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.names = ["Emil", "Tobias", "Linus"];
);
</script>

自分で試してみる

ng-optionsとng-repeat

あなたは ng-repeat 以下の指示を使用して同じドロップダウンリストを作成できます:

<select>
  <option ng-repeat="x in names">{{x}}</option>
</select>

自分で試してみる

そのため ng-repeat 指示は、配列内の各アイテムに一段のHTMLコードを繰り返し、ドロップダウンリストでオプションを作成するために使用できますが、 ng-options 指示は、ドロップダウンリストにオプションを埋めるために特別に設計されています。

どちらを使うべきですか?

あなたは使用できます ng-repeat 指示と ng-options 指示:

假设您有一个对象数组:

假设您有一个对象数组:
  $scope.cars = [
  {model : "Ford Mustang", color : "red"},
  {model : "Fiat 500", color : "white"},
{model : "Volvo XC90", color : "black"}

使用 ng-repeat

<select ng-model="selectedCar">
  ];
</select>
<h1>選択された車:{{selectedCar}}</h1>

自分で試してみる

<option ng-repeat="x in cars" value="{{x.model}}">{{x.model}}</option> 値としてオブジェクトを使用する場合、以下を使用します ng-value 代わりに

value ng-repeat オブジェクトとして使用する、

<select ng-model="selectedCar">
  <option ng-repeat="x in cars" ng-value="{{x}}">{{x.model}}</option>
</select>
<h1>選択された車は {{selectedCar.color}} {{selectedCar.model}}</h1>

自分で試してみる

使用 ng-options

<select ng-model="selectedCar" ng-options="x.model for x in cars">
</select>
<h1>選択された車:{{selectedCar.model}}</h1>
<p>その色は:{{selectedCar.color}}</p>

自分で試してみる

選択された値がオブジェクトである場合、さらに多くの情報を含むことができ、アプリケーションはより柔軟になります。

本チュートリアルでは、以下を使用します ng-options 指示

オブジェクトとしてのデータソース

前の例では、データソースは配列でしたが、オブジェクトも使用できます。

以下のように、キーワードのペアを持つオブジェクトがあります:

$scope.cars = {
  car01 : "Ford",
  car02 : "Fiat",
  car03 : "Volvo"
};

ng-options オブジェクトに対する属性の式は少し異なります:

オブジェクトとしてデータソースを使用する、x キーを表す、y 値を表す:

<select ng-model="selectedCar" ng-options="x for (x, y) in cars">
</select>
<h1>選択された車:{{selectedCar}}</h1>

自分で試してみる

選択された値は常にキーワードのペアの

キーワードのペアのオブジェクトとしてもできます:

選択された値は常にキーワードのペアの、ただし今度はオブジェクトです:

$scope.cars = {
  car01 : {brand : "Ford", model : "Mustang", color : "red"},
  car02 : {brand : "Fiat", model : "500", color : "white"},
  car03 : {brand : "Volvo", model : "XC90", color : "black"}
};

自分で試してみる

ドロップダウンリストのオプションはキー値ペアではありませんキー、または値、または値オブジェクトの属性でもあります:

<select ng-model="selectedCar" ng-options="y.brand for (x, y) in cars">
</select>

自分で試してみる