×

Html & Html5

The World's best Software Development Study Portal

AngularJS select box


  • If you want to create a dropdown list, based on an object or an array in AngularJS, you should use the ng-options or ng-repeat directive

  • Although, both can be used for dropdown list, but ng-repeat directive repeats a block of HTML code for each item in an array,

  • It can be used to create options in a dropdown list, while the ng-options directive was made especially for filling a dropdown list with options, and has at least one important advantage.

  • In AngularJS, you can create a dropdown list (select box) based on items in an array, or an object.

  • Dropdowns made with ng-options allows the selected value to be an object, while dropdowns made from ng-repeat has to be a string.

  • Note:The ng-repeat directive has its limitations, the selected value must be a string.




  • Example Using ng-options
    
         <div ng-app="myApp" ng-controller="myCtrl">
         <select ng-model="selectedName" ng-options ="x for x in names">
         </select>
         <script>
         var app = angular.module('myApp', []);
         app.controller('myCtrl', function($scope) {
         $scope.names = ["rose", "lily", "honey"];
         });
         </script>

    Output




    Example
    
           <div ng-app="myApp" ng-controller="myCtrl">
           <select ng-model="selectedCar">
           <option ng-repeat="x in cars" value="{{x.model}}">{{x.model}}</option>
           </select>
           <h1>You selected: {{selectedCar}}</h1>
           </div>
           <script>
           var app = angular.module('myApp', []);
           app.controller('myCtrl', function($scope) {
            $scope.cars = [
            {model : "Ford Mustang", color : "red"},
            {model : "Fiat 500", color : "white"},
            {model : "Volvo XC90", color : "black"}
            ];
            });
            </script>