2015-04-16 38 views
1

我想聲明兩個模型要由我的控制器加載。Ember.js:遍歷在控制器上設置的多個模型

我沒有使用modelbeforeModel,或afterModel掛鉤,因爲:

  1. 我沒有實現loading路線/模板
  2. 我可以加載每個模型獨立的頁面(如懶加載)

我使用setupController鉤在我的路線是這樣:

setupController: function(controller, model) { 
     var that = this; 

     controller.set('model', { 
      stations: that.store.find('station'), 
      packages: that.store.find('package'), 
     }); 
} 

我的控制器是Ember.Controller

爲了通過在車把這些車型我都用model.stations.content.content這讓我覺得我做錯了什麼遍歷:

{{#each station in model.stations.content.content}} 
// ..... 
{{/each}} 

是否有更好的方法來設置控制器上這些模型或使用不同的控制器類型或東西?

回答

1

你可以改變你的模型返回Ember.RSVP.hash將像一個承諾袋和散列的範圍內,您填寫的屬性stationspackages與您的數據,所以當模型得到解決它將設置散列模式爲在你的控制器型號:

[...] 
model: function() { 
    return Em.RSVP.hash({ 
     stations: this.store.find('station'), 
     packages: this.store.find('package') 
    }); 
} 
[...] 

然後在你的模板:

​​

{{#each item in model.packages}} 
    <li>{{item.name}}</li> 
{{/each}} 

(見jsbin

+0

,但我的模型是巨大的這是真的使頁面加載速度慢,這就是爲什麼我給出了一個解釋,爲什麼我沒有在 – blisstdev

1

你並不需要創建一個新的對象模型。

你可以做你的控制器中的以下內容:

setupController: function(controller, model){ 
    controller.set('model', model); 
    this.stations().then(function(value){ 
    controller.set('stations', value); 
    }); 
} 

在哪裏站是:

stations: function() { 
    return this.store.find('station'); 
} 

然後你就可以在你將使用模型以同樣的方式在你的模板中使用stations。退房this example

但控制器應該只真正裝飾一個模型,你可能會考慮創建嵌套路線(這會給你嵌套的控制器)。

+0

這個問題上使用'模型'鉤子,謝謝你的例子和所有的東西!我仍然遇到同樣的問題使用模型掛鉤,如果它需要一段時間來加載我會得到一個空白屏幕或必須實現一個加載模板。然而,將模型加載到存儲器之前,將其設置在控制器上的方法確實有用! – blisstdev

2

@如果你意識到如果你有一個大型模型或者你的AJAX請求需要很長時間,MilkyWayJoe的方法絕對是正確的方法,你的UI將會變爲空白,並且在模型加載時會變爲空白。

@Chaosekie建議我的問題的答案是等待承諾從商店加載模型,以履行然後設置控制器上的屬性。

I.e.在route

setupController: function(controller, model) { 
     this.store.find('station').then(function(stations) { 
      controller.set('stations',stations); 
     }); 
     this.store.find('package').then(function(packages) { 
      controller.set('packages', packages); 
     }); 
} 

這允許人們通過這兩種模式使用把手「正常」的方式重複:我以前做這個

{{#each package in packages}} 
// .... 
{{/each}} 

{{#each station in stations}} 
// .... 
{{/each}}