AngularJSのドロップダウン
- 前のページ AngularJS テーブル
- 次のページ AngularJS SQL
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>
- 前のページ AngularJS テーブル
- 次のページ AngularJS SQL