将下拉列表设置为AngularJS中的特定值

时间:2016-11-30 10:35:36

标签: javascript angularjs

我有以下HTML代码,并希望加载后选择下拉列表自动选择来自数据库的条目 - 在本例中来自rule.id变量。我如何在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我正在使用Angular 1.x

3 个答案:

答案 0 :(得分:2)

基本上将ng-model值设置为所需的团队对象可以进行此更改。

这应该在控制器内完成。

请查看以下代码: -

     <!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>

专注于线 $ scope.selectedAction = {&#34; name&#34;:&#34; B&#34;,&#34; id&#34; :2};

答案 1 :(得分:1)

看一下这篇文章。我认为这可能是你追求的解决方案

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

答案 2 :(得分:1)

像这样使用ng-option

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

并将您的项目ID设置为来自控制器的$scope.selectedAction = ieamId模型,从DB获取。