ru3sch
ru3sch

Reputation: 796

Ember.js get controller in view

I feel like this should be pretty straight-forward, but I'm unable to get the contents of a controller in a different view. Here is my code:

App.MapView = Ember.View.extend({
    elementId: ['map-canvas'],
    didInsertElement: function() {
        var self = this;
        var controller = this.get('controllers.markers');
    }
});

If I console.log(controller) I get undefined.

In a controller I would do something like:

App.MarkersController = Ember.ArrayController.extend({
    needs: ['map']
});
App.MapController = Ember.ObjectController.extend({
   plot: function() {
      var markers = this.get('controllers.markers');
   }
});

Upvotes: 3

Views: 9371

Answers (1)

Kingpin2k
Kingpin2k

Reputation: 47367

You place the needs on the controller that needs another controller, and where you'll be accessing the other controller.

And from a view, in order to grab the controller you do this.get('controller') and the controllers object lives on the controller, so controller.controllers.markers

Additionally, the view is only created with the controller by default if ember creates it, if you are doing something like {{view App.MapView}} it isn't creating the MapController and associating it with it, it's using the controller that was in scope when you created the view.

App.MapView = Ember.View.extend({
  elementId: ['map-canvas'],
  didInsertElement: function() {
    var self = this;
    var controller = this.get('controller.controllers.markers');
  }
});

App.MarkersController = Ember.ArrayController.extend({

});
App.MapController = Ember.ObjectController.extend({
  needs: ['markers'],
  plot: function() {
   var markers = this.get('controllers.markers');
  }
});

Check out this implementation of it:

http://emberjs.jsbin.com/ODuZibod/1/edit

Upvotes: 9

Related Questions