HTML SELECT element with angular data-binding

The Angular js ng-options directive supports the following the possible options

for array data sources:

  • label for value in array
  • select as label for value in array
  • label group by group for value in array
  • select as label group by group for value in array

for object data sources:

  • label for (key , value) in object
  • select as label for (key , value) in object
  • label group by group for (key, value) in object
  • select as label group by group for (key, value) in obj

The following simple JSFiddle shall helps you in understanding the usage of the above.

Javascript

function ControllerA($scope) {
    $scope.optionsArray = [1,2,3,4,5];
    $scope.optionsObject = {"India" : "IN" , "Singapore" : "SG", "Malaysia" : "MY"};
    $scope.optionsGroup = [
        { "country" : "India" , "city" : "Chennai"}, 
        { "country" : "India" , "city" : "Mumbai"},
        { "country" : "India" , "city" : "Delhi"},
        { "country" : "India" , "city" : "Calcutta"},
        { "country" : "Singapore" , "city" : "Singapore"}
    ];

}‚Äč

HTML

<div ng-controller="ControllerA" ng-app>
    Simple Array as options<br/>
    <select ng-options="value for value in optionsArray" ng-model="chosenA">
</select><br/>
    chosenA = {{chosenA}}<br/>
    <hr/>



    Simple options<br/>
    <select ng-options="value for (key, value) in optionsObject " ng-model="chosenO">
</select><br/>
    chosenO = {{chosenO}}<br/>
    <hr/>    



    Simple Object with key as value<br/>
    <select ng-options="value as key for (key, value) in optionsObject " ng-model="chosenO1">
</select><br/>
    chosenO1 = {{chosenO1}}<br/>
    <hr/>    


    Options Group<br/>
    <select ng-options="value.city group by value.country for value in optionsGroup" ng-model="chosenO2">
</select><br/>
    chosenO2 = {{chosenO2}}<br/>
    <hr/>        
</div>

JsFiddle

http://jsfiddle.net/ramandv/zFtkR/

This entry was posted in AngularJS, Javascript. Bookmark the permalink.

3 Responses to HTML SELECT element with angular data-binding

  1. STEVER says:

    thx it was verry helpful in my issue with select-optgroups

  2. Jay says:

    Very helpful post. Can I suggest adding one more example to your collection since I couldn’t find any examples of using a select with an array of objects where one array value is the html select “text” and one array value is the html select “value”.

    $scope.selectedAbrv = "SG";
    $scope.optionsObjectArray = [{"county":"India", "abrv":"IN"},{"county":"Singapore", "abrv":"SG"},{"county":"Malaysia", "abrv":"MY"}];




    chosenAbrv = {{selectedAbrv}}

  3. Vinoth says:

    Very Excellent ! really it is helpful … and like to share one more point.

    for keys like Inida1,Singapore2 … no need of double quotes.
    $scope.optionsObject = {India1 : “IN” , Singapore2 : “SG”, Malaysia3 : “MY”};

Leave a Reply

Your email address will not be published. Required fields are marked *