AngularJS can use arrays or objects to create a drop-down list option.
Use ng-options to create a selection box
In AngularJS, we can use the ng-option command to create a drop-down list. The list items are output cyclically through objects and arrays, as shown in the following example:
<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 = ["Ancto", "Aseoe", "BBS"];
});
</Script>
Ng-options and ng-repeat
You can also use the ng-repeat command to create a drop-down list:
Instance
<Select>
<Option ng-repeat = "x in names" >{{ x }}</option>
</Select>
The ng-repeat command uses arrays to loop through HTML code to create a drop-down list. However, the ng-options command is more suitable for creating a drop-down list. It has the following advantages:
An object that uses the ng-options option. ng-repeat is a string.
Which one should be better?
Suppose we use the following objects:
$ Scope. sites = [
{Site: "Ancto", url: "http://www.111cn.net "},
{Site: "Aseoe", url: "http://m.111cn.net "},
{Site: "BBS", url: "http://www.111cn.net/anzhuo "}
];
Ng-repeat has limitations. The selected value is a string:
Instance
Use ng-repeat:
<Select ng-model = "selectedSite">
<Option ng-repeat = "x in sites" value = "{x. url }}" >{{ x. site }}</option>
</Select>
<H1> you selected: {selectedSite }}Using the ng-options command, the selected value is an object:
Instance
Use ng-options:
<Select ng-model = "selectedSite" ng-options = "x. site for x in sites">
</Select>
<H1> you selected: {selectedSite. site }}<P> url: {selectedSite. url }}</p>
When the selected value is an object, we can obtain more information and make the application more flexible.
The data source is an object.
In the previous example, we used arrays as the data source. Below we use data objects as the data source.
$ Scope. sites = {
Site01: "Ancto ",
Site02: "Aseoe ",
Site03: "BBS"
};
Ng-options has a very different object, as shown below:
Instance
Use an object as the data source, x as the key, and y as the value ):
<Select ng-model = "selectedSite" ng-options = "x for (x, y) in sites">
</Select>
<H1> the value you selected is: {selectedSite }}
The value you select is the value in the key-value pair.
Value can also be an object in the key-value pair:
Instance
The value selected is in the value of the key-value pair, which is an object:
$ Scope. cars = {
Car01: {brand: "Ford", model: "Mustang", color: "red "},
Car02: {brand: "Fiat", model: "500", color: "white "},
Car03: {brand: "Volvo", model: "XC90", color: "black "}
};
In the drop-down menu, you can directly use the attributes of an object without using the key in the key-value pair:
Instance
<Select ng-model = "selectedCar" ng-options = "y. brand for (x, y) in sites">
</Select>