访问Ember中的父模型

时间:2013-01-31 21:19:12

标签: ember.js

所以我想将所有API密钥存储在后端的配置文件中,所以我没有将它们分散到各处。所以我认为我能够在前端创建一个模型来对/ config进行GET然后我将返回一个配置对象,其中包含我需要的任何API密钥。所以我基本上试图从ApplicationRoute访问一个模型。要清楚,请求现在发生,但我不知道如何从索引模板访问数据。我尝试了{{App.Config.apiKey}}{{apiKey}},尝试在索引控制器中设置@get.controllerFor('application').get('model')并查看是否可以查看值,但没有一个有效。我正在使用Ember 1.0.0 .4pre。感谢

所以我有这样的事情:

App = Ember.Application.create
   rootElement: '#app'

# Models
App.Store = DS.Store.extend
  revision: 11

App.User = DS.Model.extend
  firstName: DS.attr 'string'
  lastName: DS.attr 'string'
  accountType: DS.attr 'string'
  email: DS.attr 'string'
  _id: DS.attr 'string'
  password: DS.attr 'string'
  fullName: (->
    "#{@get('firstName')} #{@get('lastName')}"
  ).property('firstName', 'lastName')

App.Config = DS.Model.extend
  secret: DS.attr 'string'
  apikey: DS.attr 'string'

# Controller
# This is has validations for a form in it but I don't think its relivent
App.IndexController = Ember.ObjectController.extend()

# Routes
App.ApplicationRoute = Ember.Route.extend
  model: ->
    App.Config.find()

App.IndexRoute = Ember.Route.extend
  model: ->
    App.User.createRecord()

DS.RESTAdapter.configure "plurals", {
  config: "config"
}

App.Router.map ->
  @resource 'index'

我的模板看起来像这样:

<!--- index.html --->

<html>
  <head></head>

  <body>
    <div id="app"></div>
  </body>

</html> 

<!--- application.hbs --->
<div class="container">
  {{outlet}}
</div>

<--- index.hbs --->

<div>
  {{apiKey}} <!-- This is a value from the Config Model -->
  {{firstName}} <!-- This is a value from the User Model -->
</div>

1 个答案:

答案 0 :(得分:2)

将ApplicationController明确定义为ObjectController

App.ApplicationController = Ember.ObjectController.extend()

然后在您的ApplicationRoute中将控制器的内容设置为配置对象

App.ApplicationRoute = Ember.Route.extend
  setupController: (controller, model) ->
    this._super(controller,model);
    controller.set('content',App.Config.find(1));

或者,在索引控制器中设置配置,例如

   App.IndexRoute = Ember.Route.extend({
     setupController: function(controller,model) {
       this._super(controller,model);
       controller.set('config',App.Config.find(1));
     }
    })

然后在你的模板中

<div>
  {{config.apiKey}} <!-- This is a value from the Config Model -->
  {{config.firstName}} <!-- This is a value from the User Model -->
</div>

使用第一种方法

查看工作jsfiddle

您可以了解ember here

支持的不同类型的控制器
相关问题