AngularJS Select (selection box)
This section describes how AngularJS Select (selection box) is used.
AngularJS can use arrays or objects to create a pull-down list option.
Create a selection box with ng-options
In AngularJS we can use the ng-options directive to create a pull-down list of items that are looped through objects and arrays, as follows:
Instance
< select ng-model= "selectedName" ng-options= "x for x in names" >
< /select >
< /div >
< script >
app.controller( 'myCtrl' , function ($scope) {
$scope.names = [ "Google" , "W3Cschool" , "Taobao" ];
});
Try it out . . .
ng-options and ng-repeat
We can also use the ng-repeat instruction to create a down-and-down list:
Instance
< option ng-repeat= "x in names" > {{x}} < /option >
< /select >
Try it out . . .
The ng-repeat directive is an array that loops through HTML code to create a pull-down list, but the ng-options directive is better suited to creating a pull-down list, which has the following advantages:
An object that uses the ng-options option, ng-repeat is a string.
Which is better?
Let's say we use the following:
$scope.sites = [ {site : "Google", url : "http://www.google.com"}, {site : "W3CSchool", url : "http://www.w3cschool.cn"}, {site : "Taobao", url : "http://www.taobao.com"} ];
ng-repeat has limitations, and the value selected is a string:
Instance
Use ng-repeat :
< option ng-repeat= "x in sites" value= "{{x.url}}" > {{x.site}} < /option >
< /select >
< h1 . You have selected: >
Try it out . . .
Using the ng-options instruction, the value selected is an object:
Instance
Use ng-options :
< /select >
< h1 . You have selected: . . . selectedSite.site >
< The url is: >
Try it out . . .
When the selection value is an object, we get more information and the application is more flexible.
The data source is an object
In the previous instance we used arrays as data sources, and here we use data objects as data sources.
$scope.sites = { site01 : "Google", site02 : "W3CSchool", site03 : "Taobao" };
ng-options use objects very differently, as follows:
Instance
Use the object as the data source, x as the key, and y as the value:
< /select >
< The value you selected is: >
Try it out . . .
The value you select is value in the key-value pair.
Value can also be an object in a key-value pair:
Instance
The value selected is in the value of the key-value pair, which is an object:
car01 : {brand : "Ford" , model : "Mustang" , color : "red" },
car02 : {brand : "Fiat" , model : "500" , color : "white" },
car03 : {brand : "Volvo" , model : "XC90" , color : "black" }
};
Try it out . . .
The drop-down menu can also use the properties of the object directly without using key in the key-value pair:
Instance
< /select >
Try it out . . .