Zabs Zabs - 10 days ago 6
AngularJS Question

Set dropdown to a particular value in AngularJS

I have the following HTML code and want the select dropdown once loaded to automatically select the entry coming from the DB - in this case from the rule.id variable. How do I do this in AngularJS?

<div class="card-second-input" ng-if="rule.unfolded">
<select ng-init="rule.actionId" class="rectangle-30" ng-class="rules-option" ng-model="selectedAction" ng-options="team.name for team in teams track by team.id">
<option class="rules-option" value="">Select Team</option>
</select>
</div>


P.S I am using Angular 1.x

Answer

Basically setting the ng-model value to required team object can make this change.

This should be done inside controller.

Kindly have a look into following code:-

     <!DOCTYPE html>
          <html>
           <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
           </script>
          <body>

             <div ng-app="myApp" ng-controller="myCtrl">
                <select  class="rectangle-30" ng-model="selectedAction" ng-options="team.name for team in teams track by team.id">
                 <option  value="">Select Team</option>
                </select>
           <script>
              var app = angular.module('myApp', []);
              app.controller('myCtrl', function($scope) {

                $scope.teams = [
                   {"name": "A", "id" : 1},
                   {"name": "B", "id" : 2},
                   {"name": "C", "id" : 3},
                   {"name": "D", "id" : 4}
                ];
                $scope.selectedAction = {"name": "B", "id" : 2};
              });

           </script>

          </body>
       </html>

Focus on line $scope.selectedAction = {"name": "B", "id" : 2};