Angular:将模型正确绑定到 select 以显示默认值

Angular: properly bind a model to a select to show default value

在 angular 中,我有一个 select 元素及其模型:

 <select class="form-control" name="items" id="items" ng-model="myModel">
          <option value ="10">10</option>
          <option value ="20">20</option>
          <option value ="30">30</option>
 </select>
 {{myModel}}

在我的控制器中我有:

$scope.myModel = "20";

当页面加载时,{{myModel}}等于20,但是select框是空的,而不是显示20。稍后,如果我更改该框的值,{{myModel}} 值也会更改。它似乎正确绑定。但是我怎样才能在页面加载时显示正确的值(为什么会这样?)

这里有一个 plnkr 来查看实际问题

尝试使用 ngOptions 的方法。

<select name="myModel" id="myModel"
      ng-options=" option  for option in select track by option "
      ng-model="myModel">

Javascript :

$scope.myModel = "30";
$scope.select = [10,20,30];

这是plunker

更新--

Plunker 对于给定的脚本

fork of your original plunker 所示,问题是由 st-table 指令引起的。

此指令正在将您的 itemsPerPage 属性 更改为数字。由于limitations of the angular select directive,select的ng-model只能是字符串。

Note that the value of a select directive used without ngOptions is always a string. When the model needs to be bound to a non-string value, you must either explicitly convert it using a directive (see example below) or use ngOptions to specify the set of options. This is because an option element can only be bound to string values at present.

您有 3 个选项可以用来克服这种情况:

  1. 使用 ng-options 填充 <options>
  2. 将您的 ng-model 属性 绑定到一个单独的 属性,与传递给 st-table 的 属性 分开。
  3. 将模型显式转换为字符串,如 angular select documentation page:
  4. 上的最后一个代码示例所示
.directive('convertToNumber', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
      ngModel.$parsers.push(function(val) {
        return parseInt(val, 10);
      });
      ngModel.$formatters.push(function(val) {
        return '' + val;
      });
    }
  };
});
<select convert-to-number class="form-control" name="items" id="items" 
        ng-model="itemsByPage">
  <option value="10">10</option>
  <option value="20">20</option>
  <option value="30">30</option>
</select>​

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