EmberJS - sharing a controller / template for different routes

后端 未结 2 486
Happy的楠姐
Happy的楠姐 2020-12-28 14:23

I have a very simple CRUD application that allows for creating new objects as well as editing them.

The template used for adding a record and editing a record are al

相关标签:
2条回答
  • 2020-12-28 15:07

    Use this:

    App.YourNewRoute = Em.Route.extend ({
       controllerName: 'controllerName',
       templateName: 'templateName'
     });
    

    Only use initial name like for homeController user "home" thats it.

    Example:

    App.YourNewRoute =  Em.Route.extend ({
       controllerName: 'home',
       templateName: 'home'
    });
    

    Now you can use template and controller methods of "home".

    0 讨论(0)
  • 2020-12-28 15:11

    You were correct throughout.

    And you can use the new controller and template in edit route also.

    You have to do only two things.

    First give the template name as new in the renderTemplate hook of edit route.

    App.LocationsEditRoute = Ember.Route.extend({
      setupController: function(controller, model) {
        this.controllerFor('locations.new').setProperties({isNew:false,content:model});
      },
      renderTemplate: function() {
        this.render('locations/new')         
      }
    });
    

    As the new template is rendered the controller also will be newController, and you can have the action to point to an event in the newController.

    If you want to change the title and button text, you can have them as computed properties observing isNew property.

    Hope this helps.

    P.S: Don't forget to set the isNew property to true in the setupController of new route

    0 讨论(0)
提交回复
热议问题