【问题标题】:Select option doesnt bind with ng-model选择选项不与 ng-model 绑定
【发布时间】:2016-03-18 09:15:39
【问题描述】:

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

但是combobox的默认值被选为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 中并不总是有效会很好

【问题讨论】:

  • 将相关代码贴在 SO

标签: javascript angularjs


【解决方案1】:

用这个替换你的选择

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

【讨论】:

  • @user3334406 我已经用 Hassan Tariq 的建议替换了 Plunker 中的 select,效果很好。
  • 从选项中移除 ng-repeat
  • 好的,现在可以了 :) 非常感谢,有人可以解释为什么 ng-repeat 不起作用
【解决方案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

【讨论】:

    猜你喜欢
    • 2015-05-10
    • 1970-01-01
    • 2015-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-08
    • 2016-04-26
    相关资源
    最近更新 更多