2013-06-21 35 views
15

我想使用this.get('controllers.pack.query');獲取 App.PackQueryControllerApp.PackController,但失敗。Ember.js如何獲取需要嵌套的控制器controllerName

我認爲這個問題是灰燼使用packpack.query作爲controllerName 當它試圖獲取控制。 雖然我可以通過this.controllerFor('pack.query'), 得到控制,但灰燼說,它已被棄用,請使用needs代替

我的路由器地圖喜歡下面,我已經在App.PackController

App.Router.map(function() { 
    this.resource('pack', function() { 
     this.route('index', {path: '/:pack_id'}) 
     this.route('query'); 
    }); 
}); 

App.PackController = Ember.ObjectController.extend({ 
    needs: ['pack.query'], 
    queryPack: function() { 
     var packQueryCtrller = this.get('controllers.pack.query');    

     Ember.debug('packQueryCtrller: ' + packQueryCtrller); 
     //DEBUG: packQueryCtrller: undefined 

     packQueryCtrller.queryPack(); //faild packQuery is undefined 
    } 
}); 

App.PackQueryController = Ember.ArrayController.extend({ 
    queryPack: function (queryKey) { 
     //...do query pack 
    } 
}); 

回答

16

你應該用駱駝定義needs: ['pack.query']情況下,這不是點符號。

你的組控制器應

App.PackController = Ember.ObjectController.extend({ 
    needs: ['packQuery'], 
    queryPack: function() { 
    var packQueryCtrller = this.get('controllers.packQuery');    

    Ember.debug('packQueryCtrller: ' + packQueryCtrller); 
    //DEBUG: packQueryCtrller: undefined 

    packQueryCtrller.queryPack(); //faild packQuery is undefined 
    } 
}); 
+1

這確實不工作post ember-cli 0.2.3。請參閱@rog的解決方案。 –

35

Ember.inject.controller()應該被用來訪問控制器。使用它像這樣:

設置

... 
myController: Ember.inject.controller('pack'), 
nestedController: Ember.inject.controller('pack/query') 
... 

獲取

... 
this.get('myController'); 
this.get('nestedController'); 
... 

上面更新,以反映灰燼1.13.5的needsdeprecation答案(2015年7月19日發佈)。我已經在下面留下了舊的答案,但不應使用,除非您使用的是較早版本的Ember。


[DEPRECATED]使用needs訪問來自其它控制器嵌套控制器:

needs控制器上:

... 
needs: ['pack/query'], 
... 

然後,使用訪問它:

this.get('controllers.pack/query'); 

[DEPRECATED]從路由訪問嵌套控制器:

理想情況下,應該actions上的路線被放。如果您在控制器上使用actions中上面列出的needs模式,請考慮重構。

您可以從路由使用controllerFor像這樣訪問嵌套的控制器:

this.controllerFor('pack/query') 
+0

再次更新以反映新版本(Ember 1.11.1和ember-cli 0.2.3) – rog

+0

謝謝你,這個主題上的信息驚人地少,並且看起來似乎是通過盲目絆倒黑暗。 –

+0

再次更新以反映引入棄用原始答案的較新版本(Ember 1.13.5)。 – rog