Select List (ng-select) – AngularJS

Hey everyone,

Just a quick post on how to do up a select list in AngularJS. This one took a bit of time to work out, particularly the display/value pairing.

HTML:

<div ng-controller="MyCtrl">
    <p>
        Status: <br />
        <select name="Status" ng-model="lesson.Status" required ng-options="status.value as status.display for status in status_options"></select>   
    </p>
</div>

JavaScript:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var myApp = angular.module('myApp', []);
 
function MyCtrl($scope) {
    $scope.status_options = [
            { display: 'Enabled', value: 'enabled' },
            { display: 'Disabled', value: 'disabled' },
            { display: 'Deleted', value: 'deleted' }
        ];
 
    $scope.lesson = {
        BusinessId: 0,
        Description: null,
        Duration: 0,
        Price: 0,
        ProductId: 0,
        Quantity: 0,
        Start: "/Date(-62135596800000)/",
        Status: 'enabled', //Change to null in order to remove default
        Title: null,
        Type: null
    };
}

If you’re just following along, I’ve added a quick JSFiddle: http://jsfiddle.net/rtR6e/5/

You’ll notice that in the markup, the value is actually an index. This is pretty misleading, but Angular will actually assign the appropriate value to the model (“enabled”, “disabled”, etc).

Another thing that you can do fairly easily, is to remove the default value. Simply make the status null. You can test both these by outputting the JSON or using http://jsfiddle.net/rtR6e/5/.

Check out the following StackOverflow post for more info: http://stackoverflow.com/a/13808743/522859
Or the documentation: http://docs.angularjs.org/api/ng.directive:select

Leave a Reply