Dynamic Data Binding AngularJS SELECT Dropdown list in asp.net MVC


Binding dropdown list or select in web application development is very importent.

we can bind data to dropdown list in angularjs in two ways

1. using ng-options

ng-options is angularJS attribute can be used to dynamically generate a list of <option> elements for the <select> element using the array or object.

Advantages of ng-options

1. Reducing memory and increasing speed by not creating a new scope for each repeated instance.

2. providing more flexibility in how the <select>‘s model is assigned via the select as part of the comprehension expression

2. using ng-repeat

ng-repeat can be used on <option> element to generate list of options

this is not preferred way of binding dropdown list or select lsit

Example using ng-options
        public JsonResult GetColorsData()
        {
            List<Colors> colors = new List<Colors>()
            {
                new Colors() { Id=1,Name="Red"},
                new Colors() { Id=2,Name="White"},
                new Colors() { Id=3,Name="Blue"},
                new Colors() { Id=4,Name="Green"},
            };
            return Json(colors, JsonRequestBehavior.AllowGet);
        }

@{
    ViewBag.Title = "Dynamic data binding to dropdown list in angularjs mvc";
}

<h3>Colors</h3>
<script src="~/Scripts/angular.min.js"></script>

<div ng-app="ddlExample">
    <div ng-controller="ddlController">
        <select ng-model="selectedColor" ng-options="color.Name for color in colors track by color.Id"></select>
        <br/>
        Selected Color : {{selectedColor.Name}}
    </div>
</div>

<script>
    angular.module('ddlExample', [])
      .controller('ddlController', ['$scope', '$http', function ($scope, $http) {
          $http({
              method: 'Get',
              url: '/Home/GetColorsData'
          }).success(function (data, status, headers, config) {
              //adding colors to model
              $scope.colors = data;
              //set selected color
              $scope.selectedColor = $scope.colors[1];
          }).error(function (data, status, headers, config) {
              $scope.message = 'Error';
          });
      }]);
</script>

 

Output:

Dynamic data binding to dropdown list in angularjs mvc

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s