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

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
http://www.code-sample.com
http://www.code-sample.xyz

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.