YouTip LogoYouTip

Angularjs Select

# AngularJS Select (Select Box) AngularJS can create a dropdown list using either an array or an object. * * * ## Creating a Select Box with ng-options In AngularJS, we can use the **ng-option** directive to create a dropdown list. The list items are generated by iterating over objects and arrays, as shown in the following example: ### Example
var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.names = ["Google", "Tutorial", "Taobao"]; }); [Try it Β»](#) ng-init sets the default selected value. * * * ## ng-options vs. ng-repeat We can also use the **ng-repeat** directive to create a dropdown list: ### Example {{x}} [Try it Β»](#) The **ng-repeat** directive creates a dropdown list by iterating over an array to generate HTML code, but the **ng-options** directive is more suitable for creating dropdown lists. It has the following advantages: The option for **ng-options** is an object, while for **ng-repeat** it is a string. * * * ## Which One is Better to Use? Suppose we use the following object: $scope.sites = [ {site : "Google", url : "http://www.google.com"}, {site : "Tutorial", url : ""}, {site : "Taobao", url : "http://www.taobao.com"}]; **ng-repeat** has limitations; the selected value is a string: ### Example Using **ng-repeat**: {{x.site}}

You selected: {{selectedSite}}

[Try it Β»](#) Using the **ng-options** directive, the selected value is an object: ### Example Using **ng-options**:

You selected: {{selectedSite.site}}

URL: {{selectedSite.url}}

[Try it Β»](#) When the selected value is an object, we can access more information, making the application more flexible. * * * ## Data Source as an Object In the previous examples, we used an array as the data source. Now, let's use a data object as the data source. $scope.sites = { site01 : "Google", site02 : "Tutorial", site03 : "Taobao"}; Using an object with **ng-options** is quite different, as shown below: ### Example Using an object as the data source, **x** is the key, and **y** is the value:

You selected: {{selectedSite}}

[Try it Β»](#) The value you selected is the **value** in the key-**value** pair. The **value** in the key-**value** pair can also be an object: ### Example The selected value is in the **value** of the key-**value** pair, which in this case 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"} }; [Try it Β»](#) In the dropdown menu, you can also omit the **key** from the key-**value** pair and directly use the object's property: ### Example [Try it Β»](#)
← Angularjs SelectOs Write β†’