AngularJS Select
AngularJS can use arrays or objects to create dropdown list options.
Use ng-options to create a select box
In AngularJS we can useng-optionThe directive is used to create a dropdown list, and the list items are generated by looping through objects and arrays, as in the following example:
Example
Try it Yourself »
ng-init to set the default selected value.
ng-options and ng-repeat
We can also useng-repeatDirective to create a dropdown list:
ng-repeatThe directive loops through arrays with HTML code to create dropdown lists, butng-optionsthe directive is more suitable for creating dropdown lists, and it has the following advantages:
Usageng-optionsthe option is an object,ng-repeatis a string.
Which one should be used better?
Suppose we use the following object:
$scope.sites = [
{site : "Google", url : "http://www.google.com"},
{site : "Example", url : "http://www.example.com"},
{site : "Taobao", url : "http://www.taobao.com"}
];
ng-repeatThere are limitations, the selected value is a string:
Example
Usageng-repeat:
<option ng-repeat="x in sites" value="{{x.url}}">{{x.site}}</option>
</select>
<h1>You selected:{{selectedSite}}</h1>
Try it Yourself »
Usageng-optionsdirective, the selected value is an object:
Example
Usageng-options:
</select>
<h1>You selected:{{selectedSite.site}}</h1>
<p>The URL is:{{selectedSite.url}}</p>
Try it Yourself »
When the selected value is an object, we can obtain more information, and the application is more flexible.
The data source is an object
In the previous examples we used an array as the data source; below we will use a data object as the data source.
$scope.sites = {
site01 : "Google",
site02 : "Example",
site03 : "Taobao"
};
ng-optionsUsing objects makes a big difference, as shown below:
Example
Using an object as the data source,xas the key,yas the value:
</select>
<h1>The value you selected is:{{selectedSite}}</h1>
Try it Yourself »
The value you select is in the key-valuein the pairvalue。
valuein key-valuepair, it can also be an object:
Example
The selected value is in the key-valueof the pairvaluepair, in this case it 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 Yourself »
In the dropdown menu, you can also not usekeyin the -value pairkey, and directly use the object's properties:
Example
</select>
Try it Yourself »