Search code examples
ember.jshandlebars.jsember-clicontroller-actions

Access model in controller-action?


I'm editing an object with a form and want to save the changed object from within the controller-action which is bound to the submit-button. I don't want to bind the values directly to the template.

Here's the 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>

This is the controller admin/edit.hbs import Ember from 'ember';

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

Solution

  • Assuming that the model you want is currently the model of your ObjectController, you can do one of two things:

    1. Get the model directly:

      submitAction: function() {
          var model = this.get('model');
      }
      
    2. Pass it to the handler in the template:

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