选择选项不与ng-model绑定

时间:2016-03-18 09:15:40

标签: javascript angularjs

我有一个AllCountries和SelectedCoutry的对象。 我想列出<select>上的所有国家/地区,并选择带有ng-model的选项,其值为SelectedCountry。

但是,组合框的默认值被选为null。

示例:

angular.module('ngPatternExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
      $scope.OBJ = {
                    "OBJ": {
                      "AllCountries": [
                        {
                          "country": "USA",
                          "id": 1
                        },
                        {
                          "country": "Mexico",
                          "id": 2
                        },
                        {
                          "country": "Canada",
                          "id": 3
                        }
                      ],
                      "SelectedCountry": {
                        "country_id": 1,
                      }
                    }
                }
                
      $scope.AM = $scope.OBJ.OBJ;
    }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="ngPatternExample">
<div ng-controller="ExampleController">
  selected country: {{AM.SelectedCountry.country_id}} <br/>
  <select class="form-control" ng-model="AM.SelectedCountry.country_id">
    <option value=""> --- </option>
    <option ng-repeat="co in AM.AllCountries" value="{{co.id}}"> {{co.country}} </option>
  </select>
</div>
  </body>

http://plnkr.co/edit/PI3tOrIMSTMwGC0rYA5q?p=preview

p.s一个很好的解释为什么它在Angular中不起作用将是很好的

2 个答案:

答案 0 :(得分:3)

用此

替换您的选择
<select class="form-control"  ng-options="co.id as co.country for co in OBJ.OBJ.AllCountries" ng-model="AM.SelectedCountry.country_id">
    <option value=""> --- </option>
</select>

答案 1 :(得分:2)

使用ngOptions指令而不是自己在选择框中重复选项。

<select 
  class="form-control"
  ng-model="AM.SelectedCountry.country_id"
  ng-options="co.id as co.country for co in AM.AllCountries">
    <option value=""> --- </option>
</select>

更新了plunk: http://plnkr.co/edit/FZcJVkJQlbLM3k544s8S?p=preview