Zabs
Zabs

Reputation: 14142

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

Upvotes: 0

Views: 1726

Answers (3)

rvchauhan
rvchauhan

Reputation: 89

Use ng-option like this

ng-options="team.id as team.name for team in teams track by team.id"

And set your item Id to model like this $scope.selectedAction = ieamId from controller which get from DB.

Upvotes: 1

Tim Smart
Tim Smart

Reputation: 178

Take a look at this post. I think this may be the solution you are after

How to set a selected option of a dropdown list control using angular JS

Upvotes: 1

Abhishek Srivastava
Abhishek Srivastava

Reputation: 187

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};

Upvotes: 2

Related Questions