Latest web development tutorials

AngularJS Select (check box)

AngularJS can create a drop-down list of options to use an array or object.

Create a selection box using ng-options

In AngularJS we can useng-option command to create a drop-down lists, list items through objects and arrays cycle of the output, following examples:


<Div ng-app = "myApp " ng-controller = "myCtrl">

<Select ng-model = "selectedName " ng-options = "x for x in names">
</ Select>

</ Div>

var app = angular.module ( 'myApp' , []);
app.controller ( 'myCtrl', function ( $ scope) {
$ scope.names = [ "Google", "w3big", "Taobao"];
</ Script>

try it"

ng-options and ng-repeat

We can also useng-repeat directive to create a drop-down list:


<Option ng-repeat = "x in names"> {{x}} </ option>
</ Select>

try it"

ng-repeat instruction is to loop through the array of HTML code to create drop-down list, but ng-optionscommand better suited for creating drop-down list, it has the following advantages:

An object usingng-options options,ng-repeat is a string.

It should be used which is better?

Suppose we use the following objects:

$scope.sites = [
    {site : "Google", url : ""},
    {site : "w3big", url : ""},
    {site : "Taobao", url : ""}

ng-repeat has its limitations, the chosen value is a string:



<Select ng-model = "selectedSite ">
<Option ng-repeat = "x in sites" value = "{{x.url}}"> {{}} </ option>
</ Select>

<H1> Your choice is: {{selectedSite}} </ h1>

try it"

Useng-options command, select the value of an object:



<Select ng-model = "selectedSite " ng-options = " for x in sites">
</ Select>

<H1> Your choice is: {{}} </ h1>
<P> URL is: {{selectedSite.url}} </ p>

try it"

When you select the value is an object, we can get more information and applications more flexible.

Data source object

Previous example we use an array as a data source, we have the following data objects as the data source.

$scope.sites = {
    site01 : "Google",
    site02 : "w3big",
    site03 : "Taobao"

ng-options using objects are very different, as follows:


Using the object as a data source,x is the key (key),y is a value (value):

<Select ng-model = "selectedSite " ng-options = "x for (x, y) in sites">
</ Select>

<H1> value you choose: {{selectedSite}} </ h1>

try it"

Your choice is value in key- value pairs.

value in the key- value pairs can also be a target:


Select the value in the key- value of the value, which is that 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"

May not be used key -value pairs key, use the properties of an object directly in the drop-down menu:


<Select ng-model = "selectedCar " ng-options = "y.brand for (x, y) in cars">
</ Select>

try it"