我正在尝试使用Emberjs 需要api *从评论控制器访问Postscontroller。 PostController由路由支持,而我不希望注释的控制器有路由。
在评论控制器中,我有需要:['posts','postsShow'] 。在评论控制器中,当我使用以下命令运行控制台日志时:
console.log( this.get('controllers.postsShow') );
console.log( this.get('controllers.posts') );
在控制台中我看到:
<EmBlog.PostsShowController:ember396> { target=<EmBlog.Router:ember316>, namespace=EmBlog, store=<EmBlog.Store:ember336>
<EmBlog.PostsController:ember304> { target=<EmBlog.Router:ember316>, namespace=EmBlog, store=<EmBlog.Store:ember336>
但是,当我尝试访问PostsShowController或PostsController的控制器内容时,它总是返回发布未定义。这些是我尝试过的各种方法,但仍然有发布未定义:
var post = this.get('controllers.posts').get('content');
or
var post = this.get('controllers.posts.content');
我还尝试从以下内容中获取“评论”:
var post = this.get('controllers.posts')
var comment = post.get('comments');
or
comment = post.comments;
我仍然收到错误:
TypeError: post is undefined comment = post.comments;
TypeError: post is undefined var comment = post.get('comments');
这也意味着:
var post = this.get('controllers.posts.model').get('store.transaction');
also returns post is undefined.
这是jsfiddle,代码的相关部分粘贴在下方:
EmBlog.PostsNewController = Ember.ObjectController.extend({
content: null
});
EmBlog.PostsShowController =
Ember.ObjectController.extend({
content: null
});
EmBlog.CommentNewController = Em.ObjectController.extend({
needs: ['posts', 'postsShow'],
isAddingNew: false,
addComment: function(body){
console.log( this.get('controllers.postsShow') );
console.log( this.get('controllers.posts') );
var post = this.get('controllers.posts.content');
store = post.get('store.transaction');
}
});
非常感谢
答案 0 :(得分:6)
那是因为posts
控制器是空的。您填写PostIndexController
中的帖子,而不是PostsController
。
检查路线:
EmBlog.PostsRoute = Ember.Route.extend({
});
EmBlog.PostsIndexRoute = Ember.Route.extend({
model: function(){
return EmBlog.Post.find();
},
setupController: function(controller, model){
controller.set('content', model);
}
});
所以你应该做
needs: ['postsIndex', 'postsShow']
然后:
this.get('controllers.postsIndex.content')
或修正您的路线:
EmBlog.PostsRoute = Ember.Route.extend({
model: function() {
return EmBlog.Post.find();
}
});
EmBlog.PostsIndexRoute = Ember.Route.extend({
model: function(){
return this.modelFor('posts');
},
setupController: function(controller, model){
controller.set('content', model);
}
});