Reputation: 13
I am creating a basic ember app with javascript object arrays(Don't want to use anything else until I get a firm grasp). I am having trouble implementing functionality to add new users. I'm not sure what to add to my controller.
In the template:
<form {{action 'add-student' on="submit"}}>
{{input id="add-student" type="text" placeholder="student name" value=name}}
<button class="btn btn-default" type="submit">Add</button>
</form>
My students route: import Ember from 'ember';
var students = [{
id: 1,
name: 'John',
}, {
id: 2,
name: 'Vanessa'
}];
export default Ember.Route.extend({
model() {
return students;
}
});
Upvotes: 0
Views: 44
Reputation: 2048
For route you might want something like this. Using Ember.RSVP.hash it allows you to return 1-n properties from model.
export default Ember.Route.extend({
model() {
const store = this.get('store');
return Ember.RSVP.hash({
students: Ember.A([
store.createRecord('student', { name: 'Vanessa'})
]),
someOtherModelThing: store.find('xx')
})
}
});
In the template you would want something like this.
{{input type="text" value=name}}
<button class="btn btn-default" {{action "addNewStudent" name}}>Add</button>
And to handle addNewStudent you would need to write an action in controller.
...
actions: {
addNewStudent(studentName) {
const store = this.get('store');
var newStudent = store.createRecord('student', {name: studentName});
this.get('model.students').pushObject(newStudent);
}
}
...
And if you're also looking to save them you might wanna have save button with an action 'saveStudents'.
saveStudents: function() {
return Ember.RSVP.all(this.get('model.students').invoke('save'))
}
Showing the list of students in the template.
{{#each model.students as |student|}}
<p> {{student.name}}
{{/each}}
All of this can be achieved without using ember-data (store.createRecord etc..). using plain JSON and Ajax to save data.
Upvotes: 1