Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup multiple controllers in the same route in ember.js?

I am relatively new to ember.js. I have two models User and Role

App.User = DS.Model.extend({
    name: DS.attr('string'),
    roles: DS.hasMany('role')
});

App.Role = DS.Model.extend({
    name: DS.attr('string')
});

In my application I need to assign and/or remove roles for one user. For that I need to loop and compare two controllers - roles (from user has roles) against all available roles

I get the roles assigned to users by doing this in the user/edit template

Assigned Roles: {{#each role in roles}}*{{role.name}}{{/each}}

But then how do I have another RolesController in the same route that will have all the available roles independent of the user? If I do a setupController in UserEditRoute that will create a clash of names for RolesController.

My target is to have all the roles listed with checkboxes. The roles that are already assigned to the user will be checked and the others will be unchecked

jsfiddle link

like image 829
kaushikb9 Avatar asked Oct 15 '13 12:10

kaushikb9


1 Answers

In the User controller you can set the needs property to tell ember to wire roles controller.

You should also to assign the model for this controller, so you set the setupController hook of the UsersEditRoute and yo have your roles listed

App.UsersEditRoute = Ember.Route.extend({
  setupController: function(controller,model) {
        controller.set('model', model);//UsersEditController
        this.controllerFor('roles').set('model',this.store.find('role'));
  }
});

Controllers

App.UsersEditController = Em.ObjectController.extend({
    needs: "roles",
    rolesController: Ember.computed.alias("controllers.roles")
});
App.RolesController = Em.ArrayController.extend({});

And finally template

  <script type="text/x-handlebars" data-template-name="users/edit">
    <h3>User Edit</h3>
      <p>Name: {{name}}</p>
      <p>Assigned Roles: {{#each userRole in roles}}&nbsp;*{{userRole.name}}{{/each}}</p>
      <p>Available Roles:{{#each role in rolesController}}&nbsp;*{{role.name}}{{/each}}</p>
  </script>

jsfiddle http://jsfiddle.net/tXFkZ/3/

like image 160
Edu Avatar answered Nov 14 '22 22:11

Edu