初始ng模型值未正确设置选择

时间:2017-05-09 08:23:47

标签: javascript angularjs typescript

给定以下角度分量with a working plunker

export const AppComponent = {
  template: 'see below'
  controller: class AppComponent {
    static $inject = ["$http"];
    constructor(public $http) {
    }
    $onInit() {
      this.$http.get("types.json").then(_ => this.types = _.data);
      this.$http.get("docs.json").then(_ => this.documents = _.data);
    }
  }
};

使用模板

<div>
    <h3>Types</h3>
    <div ng-repeat='document in $ctrl.types'>{{document.name}}</div>

    <h3>Docs</h3>
    <div ng-repeat="status in $ctrl.documents">
        <span ng-bind="status.documentType.name"></span>
        <ul ng-repeat="document in status.correspondence">
            <li>{{document.name}}</li>
            <li>
                {{document.documentTypeId}}
                <!-- ng options: can't seem to get correct mapping for just the `ID`,  
                     it always binds the while type object.
                     ng-options="type.name for type in $ctrl.types track by type.id"
                -->
                <select
                    ng-model="document.documentTypeId">
                    <option ng-repeat="type in $ctrl.types" value="{{type.id}}">{{type.name}}</option>
                </select>
            </li>
        </ul>
    </div>
</div>

通过点击特定类型更改时,select的初始值未设置,模型已更新正确。

  

为什么在页面加载时没有从模型中正确设置选择值?

2 个答案:

答案 0 :(得分:0)

ngOptions支持自定义子属性成为下拉列表的ngModel。像这样,

ng-options="type.id as type.name for type in $ctrl.types"
            ^^^^^^^^^^

可以读作value as label for collection。但是,这不能与track by一起使用。你必须选择one or other.

而且,在这种情况下,我们可以摆脱track by因为我们没有太复杂的对象来迭代。

working example

答案 1 :(得分:0)

您可以使用此代码:

<select 
                ng-options="type.id as (type.name) for type in $ctrl.types"
                ng-model="document.documentTypeId">
            </select>

本准则将解决问题。