angularjs如何在下拉列表中填充选定的值

时间:2017-02-02 19:57:21

标签: javascript jquery angularjs

我有两个相互依赖的选定下拉列表。例如plunker here,我想填充下拉列表的值,而不是显示&#34;选择此处&#34;价值,我希望在第一次下拉中显示法国,在第二次下拉时显示单向。我试过<option value="selectedPlan">{{selectedPlan}}</option>,但它没有显示任何内容。 感谢

我的代码:

<!doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Example</title>


  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>



</head>

<body ng-app="selectExample">
  <script>
    angular.module('selectExample', [])
      .controller('ExampleController', ['$scope', function($scope) {

        $scope.chooseCountries = [{
          name: "France",
        }, {
          name: "Gibraltar",
        }, {
          name: "Malta",
        }];
        $scope.choosePlans = [{
          plan:"One Way"
        }, {
           plan:"Two Way"
        }];

        $scope.selectedCountry = "";
        $scope.selectedPlan = "";
      }]);
  </script>
  <div ng-controller="ExampleController">

    <hr>
    ng-options
    <hr>

    <select ng-model="selectedCountry"
      ng-options="country.name  for country in chooseCountries">
      <option value="">Select here</option>
    </select>

     <select ng-model="selectedPlan" 
      ng-options="plan.plan  for plan in choosePlans">
        <option value="">Select here</option>
    </select>
  </div>
</body>

2 个答案:

答案 0 :(得分:0)

将options数组中的一个对象分配给模型:

    $scope.selectedCountry = $scope.chooseCountries[0];
    $scope.selectedPlan = $scope.choosePlans[1];

DEMO

答案 1 :(得分:0)

如果通过&#34;同步&#34;你的意思是应该选择相同的索引进行第二次选择,然后就是。

<select 
  ng-init="selectedCountry = chooseCountries[0]"
  ng-model="selectedCountry"
  ng-change="selectedPlan = choosePlans[chooseCountries.indexOf(selectedCountry)]"
  ng-options="country.name for country in chooseCountries"> 
</select>
<select 
  ng-model="selectedPlan"
  ng-init="selectedPlan = choosePlans[0]"
  ng-options="plan.plan for plan in choosePlans">
</select>

如果它只是初始化选择,比如索引0,只需忽略上面的ng-change即可。