Ember.js如何获得需要的控制器,它是嵌套的controllerName

Isa*_*ddo 15 controller nested-routes ember.js

我想用this.get('controllers.pack.query');得到 App.PackQueryControllerApp.PackController,但失败了.

我认为这个问题是灰烬使用pack不是pack.query因为controllerName 当它试图获取控制.虽然我可以得到控制器this.controllerFor('pack.query'),但是Ember说它已被弃用,请needs改为使用

我的路由器地图喜欢下面,我已经定义needs: ['pack.query']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
    }
});
Run Code Online (Sandbox Code Playgroud)

rog*_*rog 35

Ember.inject.controller()应该用来访问控制器.像这样使用它:

设置

...
myController: Ember.inject.controller('pack'),
nestedController: Ember.inject.controller('pack/query')
...
Run Code Online (Sandbox Code Playgroud)

入门

...
this.get('myController');
this.get('nestedController');
...
Run Code Online (Sandbox Code Playgroud)

上述答案已更新,以反映Ember 1.13.5(2015年7月19日发布)中的needs 弃用.我已经在下面留下了旧的答案,但除非你使用旧版本的Ember,否则不应该使用它.


[DEPRECATED]使用needs以下方法从其他控制器访问嵌套控制器:

needs在控制器上设置:

...
needs: ['pack/query'],
...
Run Code Online (Sandbox Code Playgroud)

然后使用:访问它:

this.get('controllers.pack/query');
Run Code Online (Sandbox Code Playgroud)

[DEPRECATED]从路径访问嵌套控制器:

理想情况下,actions应该放在路线上.如果您在控制器上使用上述needs模式actions,请考虑重构.

您可以使用controllerFor如下方式从Route访问嵌套控制器:

this.controllerFor('pack/query')
Run Code Online (Sandbox Code Playgroud)


Wal*_*ile 16

你应该使用驼峰的情况,而不是点符号.

你的包控制器应该是

 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
   }
});
Run Code Online (Sandbox Code Playgroud)