Toran Billups
Toran Billups

Reputation: 27399

How to get a parent routes model from inside controller action?

Inside my route for "appointments" below I can reach up and get the model for the parent "day"

App.Router.map(function(match) {                                          
    this.resource("day", { path: "/day/:day" }, function() {              
        this.resource("appointments", { path: "/appointments" }, function() {
            this.route("new", { path: "/:appointment_start/new" });
            this.route("edit", { path: "/:appointment_id/edit" });        
        });                                                               
    });                                                                   
});

But when I'm deep inside the new or edit routes, how can I reach up (from within the actions handler) and grab the parent "day" model like I did in the route?

App.AppointmentsEditController = Ember.Controller.extend({                
    actions: {
        updateAppointment: function(appointment) {
            var day = this.get('??');
        }
    }
});

Update

The final controller code now looks like this

App.AppointmentsEditController = Ember.Controller.extend({       
    needs: 'day',         
    actions: {
        updateAppointment: function(appointment) {
            var day = this.get('controllers.day');
        }
    }
});

Upvotes: 5

Views: 2192

Answers (2)

Artur Małecki
Artur Małecki

Reputation: 1506

There is simple way to do it. In AppointmentsEditController add

needs: "day"

Then you can access to day controller via this.get('controllers.day').

I always use something like this:

App.CommentsControler = Ember.Controller.extend({
    needs: "post",
    postBinding: "controllers.post",
    ...
    postName: function() {
        return this.post.name;
    }.property("post.name")
})  

Take a look of this article http://emberjs.com/guides/controllers/dependencies-between-controllers/

I hope this help :)

Upvotes: 2

sjmog
sjmog

Reputation: 161

Toran - sorry to add this as an extra answer, I can't comment yet - yes, it should work for free. You can access controllers.post from within the actions block like this:

var postController = this.get('controllers.post')

Upvotes: 4

Related Questions