AngularJS using the Select Element

Printer-friendly version

AngularJS makes the rendering of an HTML select element quite simple, especially for dynamic options that can be retrieved via a backend service. The directive that AngularJS uses for select elements defined the ng-required attribute that is available for input elements and an ng-options attribute that can be used to generate option elements from arrays and objects, see Listing 1 below.

<!DOCTYPE html>

<html ng-app="todoApp">

<head>

    <title>Select Example</title>

    <link data-require="bootstrap@*" data-semver="3.3.5" rel="stylesheet" 

href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />

    <script data-require="angular.js@1.4.7" data-semver="1.4.7" 

src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>

    <script>

        angular.module("todoApp", [])

            .controller("mainCtrl", function($scope) {

                $scope.todos = [

                    {id: 1, task: "Register for VS Live Vegas", complete: false},

                    {id: 2, task: "Learn AngularJS", complete: false},

                    {id: 3, task: "Scribe Online Training", complete: true}

                ];

            });

    </script>

</head>

<body>

    <div id="todoPanel" class="panel" ng-controller="mainCtrl">

        <form name="myForm" novalidate>

            <div class="well">

                <div class="form-group">

                    <label>Select an Task:</label>

                    <select ng-model="selectedOption" ng-options="item.task for item in todos"></select>

                </div>

            </div>

            <div class="well">

                <p>Selected Option: {{selectedOption || 'None'}}</p>

            </div>

        </form>

    </div>

</body>

</html>

Listing 1. An example of using Select with ng-options

 

In Listing 1, a data model is defined that contains a few to-do items with an id, task and complete properties. For the select element, the ng-options attribute is setup such that an option element is generated for each of the items.

<select ng-model="selectedOption" ng-options="item.task for item in todos"></select>

This is the basic ng-options expression, and in the format <label> for <variable> in <array>. AngularJS will generate an option element for each object in the array and set the contents to be the label displayed. The select element generates the following HTML:

<select ng-model="selectedOption" ng-options="item.task for item in todos" 

    class="ng-valid ng-dirty ng-valid-parse ng-touched">

    <option value="?" selected="selected"></option>

    <option value="1">Register for VS Live Vegas</option>

    <option value="2">Learn AngularJS</option>

    <option value="3">Scribe Online Training</option>

</select>

Listing 2. Select markup

 

 

Figure 1. Initial page load

 

Using the ng-options attribute is similar to using the ng-repeat directive, but with some additions and quirks that are particular to select elements. See the AngularJS documentation for more info.

Notice that the output from the select element contains an option element whose value attribute is a question mark and that has no content. AngularJS generates this when the property specified by the ng-model attribute is undefined. You can replace this default option element by adding your own with an empty value, as shown in Listing 3.

<select ng-model="selectedOption" ng-options="item.task for item in todos">

    <option value="">(Select a Task...)</option>

</select>

Listing 3. Replacing the default option element

 

By default, choosing an option in a select element causes the ng-model expression to be updated with the object in the collection. You can see this by loading the page in a browser and making a selection. There is a data binding at the bottom of the page that shows the selectedOption model property, which is implicitly defined by the select element and shows the selected object, see Figure 2.

 

 

Figure 2. With a selected option and default ng-model value

 

You don’t always want to use the complete source object to set the ng-model value, so you can use a slightly different expression for the ng-options attribute to specify one of the properties from the object, as shown in Listing 3.

Listing 12-17. Specifying a Property as the ng-model Value in the forms.html File

<select ng-model="selectedOption" ng-options="item.id as item.task for item in todos">

    <option value="">(Select a Task...)</option>

</select>

Listing 4. Specifying a property as the ng-model value

 

The expression is in the form <selected property> as <label> for <variable> in <array>.  In Listing 4, the item.id is the value that will used when an option is selected. You can see the effect of this change in Figure 3.

 

 

Figure 3. Using a property for the ng-model value

 

Angular makes in quite easy to get your select elements populate as you can see. The todos in this case were static objects, but they can easily be retrieved from a backend database or service.  The ng-options can also be used to group items together based on the value of a property. So be sure to check out the documentation for additional information.

About the Author:

TopLine Strategies delivers the complete integration and development of sales, marketing and customer service technologies that enable corporate clientele to improve revenue streams and strengthen customer interactions. Our project management and consulting is designed to achieve timely delivery, 100 percent user adoption of the technologies we implement and deliver measurable returns on investments for our clients.

Comments (0)

Related Blogs

In 2018, the React Native team focused on large scale re-architecture of React Native. They are planning to better support the thriving population of React Native users and collaborators.

TheReact Native Open Source roadmap was announced in Q4 2018 after they decided to invest more in the React Native open source community.