控制器存储应用程序的状态。路由器管理应用程序的不同状态。你是对的,每条路由只有一个控制器,但你也可以访问其他控制器。
假设这是您的html:
<script type="text/x-handlebars" data-template-name="application">
<div class="main-content">
{{outlet}}
</div>
</script>
<script type="text/x-handlebars" data-template-name="index">
<div class="nav-bar">
<div class="user">
{{#if isLoggedIn}}
<div class="user-name">{{userName}}</div>
{{else}}
<button {{action "login" target="App.UserController"}}>
Login
</button>
{{/if}}
</div>
</div>
<div class="content">some other amazing content here</div>
</script>
和JS:
var App = Ember.Application.create({
LOG_TRANSITIONS: true,
rootElement: '#ember-app'
});
App.Router.map(function () {
this.route('user');
});
App.IndexRoute = Ember.Route.extend({
setupController: function(controller, model) {
this.controller.set('isLoggedIn', this.controllerFor('user').get('isLoggedIn'));
}
});
App.UserController = Ember.ObjectController.extend({
isLoggedIn: false,
userName: 'emberjs',
login: function () {
this.set('isLoggedIn', true);
}
});
App.NavbarView = Ember.View.create({
loggedInBinding: Ember.Binding.oneWay('App.UserController.isLoggedIn')
});
如果你需要从你的路由访问另一个控制器,你可以这样做:
App.IndexRoute = Ember.Route.extend(function () {
setupController: function () {
var userController = this.controllerFor('user');
console.log('this is a user controller instance', userController);
}
});