【问题标题】:Access model in controller-action?控制器动作中的访问模型?
【发布时间】:2015-01-31 18:51:55
【问题描述】:

我正在使用表单编辑一个对象,并希望从绑定到提交按钮的控制器操作中保存更改的对象。我不想将值直接绑定到模板。

这是admin/edit.hbs

<form>
    <label>Title
      <input name="title" type="text" {{ bind-attr value=title }} />
    </label>
    <label>Permalink
      <input name="permalink" type="text" {{ bind-attr value=permalink }} />
    </label>
    <label>Post
      {{textarea value=body cols="80" rows="12"}}
    </label>
  <button {{ action 'submitAction' }}>Submit</button>
</form>

这是控制器admin/edit.hbs 从 'ember' 导入 Ember;

export default Ember.ObjectController.extend({    
  actions: {
      submitAction: function() {
        var newTitle = this.get('title');
        // how to access the model here?
      }
    }
});

【问题讨论】:

    标签: ember.js handlebars.js ember-cli controller-actions


    【解决方案1】:

    假设您想要的模型当前是您的ObjectController 的模型,您可以做以下两件事之一:

    1. 直接获取模型:

      submitAction: function() {
          var model = this.get('model');
      }
      
    2. 将其传递给模板中的处理程序:

      // admin/edit.hbs
      <button {{action 'submitAction' model}}>Submit</button>
      
      // admin/edit.js
      submitAction: function(model) {
      
      }
      

    【讨论】:

      【解决方案2】:

      ObjectController 中,模型存储为……model。你可以这样访问它:

      var model = this.get('model');
      model.set('title', newTitle);
      

      如果您没有使用 ObjectController 自动将 getset 调用绑定到对象的功能,您可能不应该使用 ObjectController。您列出的代码将直接从输入字段设置模型的title

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-26
        • 1970-01-01
        • 1970-01-01
        • 2013-02-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多