set default value in dropdown list in angularjs

set default value in dropdown list in angularjs

This is interesting question, how to set default value in option or drop-down list using angular. We can achieve the angular directive with two way binding ng-model and ng-option also.

In the below example code, bind the collection on ng-option and countryId from country collection on ng-model.

Go to live demo link http://embed.plnkr.co/Wlw62X/preview

Using the we can bind the collection in option or drop-down list.



If you want to set the default value, that time need to add default countryId within the controller $scope.

The code look like [$scope.register.countryId = "1";]  // This is the default countryId.

The example code as given below.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
    <script>
        angular.module("myapp", [])
          .controller("MyController", function ($scope) {
              $scope.register = {};
              $scope.register.countryId = "1";

              $scope.register.countries = [{
                  id: "1",
                  name: "India"
              }, {
                  id: "2",
                  name: "USA"
              }, {
                  id: "3",
                  name: "UK"
              }, {
                  id: "4",
                  name: "Nepal"
              }];
          });
    </script>
</head>
<body ng-app="myapp">
    <div ng-controller="MyController">
        <div>
            Country Name :  <select ng-model="register.countryId" ng-options="country.id as country.name for country in register.countries"></select>
        </div>
        <div>
            Country-Id : {{register.countryId}}
        </div>
    </div>
</body>
</html>

The demo output: go to link http://embed.plnkr.co/Wlw62X/preview






ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

www.code-sample.com/. Powered by Blogger.
^