How to configure multiple controllers on 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 a single user. To do this, I need to build and compare two controllers - roles (from the user have roles) from all available roles

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

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

But how can I add another RolesController on the same route, which will have all the available roles, regardless of the user? If I do setupController in UserEditRoute, which will create a name clash for RolesController.

My goal is to have all roles listed with checkboxes. Roles that are already assigned to the user will be checked, and the rest will be removed.

jsfiddle link

+6
source share
1 answer

In the user controller, you can set the needs property to tell ember about the role controller connection.

You must also assign a model to this controller, so you set the hook for setupController for UsersEditRoute, and your roles are 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 the pattern

  <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/

+15
source

Source: https://habr.com/ru/post/955982/


All Articles