Dougui
Dougui

Reputation: 7232

Not able to share dependencies on a controller

I have an application running with Ember 1.12.0. I have a simple template called /app/templates/repositories.hbs with this content :

{{controllers.user.login}}

I added this in the controller app/controllers/repositories.js :

import Ember from 'ember';

export default Ember.ArrayController.extend({
  needs: "user",
});

I have this route :

import Ember from 'ember';

export default Ember.Route.extend({
  model: function(params) {
    var user = this.modelFor('user');
    console.log(user);
    return Ember.$.getJSON('https://api.github.com/users/'+user.login+'/repos');
  }
});

And this router :

import Ember from 'ember';
import config from './config/environment';

var Router = Ember.Router.extend({
  location: config.locationType
});

Router.map(function() {
  this.route('index', {path: '/'} );
  this.resource('user', {path: '/users/:login'}, function() {
    this.resource('repositories');
  });
});

export default Router;

According to the documentation. I should show the user login but I have just nothing. It show the user object in the console but not in the view.

Is the a solution ?

Upvotes: 0

Views: 20

Answers (1)

Kuba Niechciał
Kuba Niechciał

Reputation: 974

If I understand correctly, you have a user model fetched in user route (as you can see it in console, the modelFor works properly). However, you are trying to get login object on user controller - I think that it's not defined. What you really want to get is login property of the object that is the model for user route (probably it's the user, but you didn't posted your user route code).

To use these two models in one controller you don't need to share these controllers. All you need is the model for user route. Thus, you can leave your model hook as follows:

model: function(params) {
  return Ember.$.getJSON('https://api.github.com/users/'+user.login+'/repos');
}

And write your setupController method as follows:

setupController: function(controller, model) {
  controller.set("model", model);
  controller.set("user", this.modelFor("user");
}

And in your template you would have your repos from AJAX and the user property with that property.

{{user.login}}

On the other hand, you could, with some fixes, use the shared user controller obtaining same effect, but it's not what you need - you need only the model for that controller, not the whole object.

Upvotes: 1

Related Questions