2017-05-09 52 views
0

給定以下角度分量with a working plunker初始ng模型值未設置正確選擇

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的inital沒有設置值,當值通過點擊特定類型的改變模型正確更新

爲什麼在頁面加載時,模型中的選擇值沒有正確設置?

回答

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

0

您可以使用此代碼:

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

這個代碼將被解決的問題。