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>