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>

of-options vsof-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">
  <option ng-repeat="x in cars" value="{{x.model}}">{{x.model}}</option>
</select>

<h1>You selected: {{selectedCar}}</h1>

値をオブジェクトとして使用する場合は、ng-value次のインシードを使用してvalueください。

ng-repeatオブジェクトとしての使用:

<select ng-model="selectedCar">
  <option ng-repeat="x in cars" ng-value="{{x}}">{{x.model}}</option>
</select>

<h1>You selected a {{selectedCar.color}} {{selectedCar.model}}</h1>

使用ng-options

<select ng-model="selectedCar" ng-options="x.model for x in cars">
</select>

<h1>You selected: {{selectedCar.model}}</h1>
<p>Its color is: {{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>You selected: {{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>