如何通过ember中的hbs文件传递参数

问题描述:

我已经使用ember.js创建了一个应用程序。 这里我无法得到从tasks.hbs传递给subtasks.hbs的参数值。我可以从subtasks.hbs中的tasks.hbs传递参数值并将其打印在subtasks.hbs中吗?如何通过ember中的hbs文件传递参数

应用/模板/ tasks.hbs:

{{outlet}} 
<h1>Tasks</h1> 
{{#each model as |task|}} 
    <div class="well"> 
     <h4>{{#link-to 'tasks.edit' task.id}}{{task.title}}{{/link-to}}</h4> 
     <small>Created: {{format-date task.created}}</small><br> 
     <small>Due: {{format-date task.date}}</small> 
     <h5>Priority: {{task.priority}}</h5> 
     <p>{{task.description}}</p> 
     <button {{action 'deleteTask' task.id}} class="btn btn-danger">Delete</button><hr> 

     {{#link-to 'subtasks.subnew' task.id}}<button class="btn btn-primary">Create SubTask</button>{{/link-to}} 

     {{#link-to 'subtasks' task.id}}<button class="btn btn-primary">Show SubTasks</button>{{/link-to}} 
    </div> 
{{/each}} 

应用/模板/ subtasks.hbs:

{{outlet}} 
<h1>SubTasks</h1> 
<h2>{{task_id}}</h2> 
{{#each model as |subtask|}} 
<h1>{{subtask.id}}</h1> 
{{#if model.id subtask.tno}} 
    <div class="well"> 
     <h4>{{#link-to 'subtasks.subedit' subtask.id}}{{subtask.subtitle}}{{/link-to}}</h4> 
     <small>Created: {{format-date subtask.subcreated}}</small><br> 
     <small>Due: {{format-date subtask.subdate}}</small> 
     <h5>Priority: {{subtask.subpriority}}</h5> 
     <p>{{subtask.subdescription}}</p> 
     <button {{action 'deleteSubTask' subtask.id}} class="btn btn-danger">Delete</button> 
    </div> 
{{/if}} 
{{/each}} 

应用程序/路由/ tasks.js:

import Ember from 'ember'; 

export default Ember.Route.extend({ 
    model(){ 
     return this.store.findAll('task'); 
    } 
}); 

应用/routes/subtasks.js:

import Ember from 'ember'; 

export default Ember.Route.extend({ 
    model(){ 
     return this.store.findAll('subtask'); 
    } 
}); 

router.js:

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

const Router = Ember.Router.extend({ 
    location: config.locationType, 
    rootURL: config.rootURL 
}); 

Router.map(function() { 
    this.resource('tasks', function() { 
    this.route('new'); 
    this.route('edit', {path: '/edit/:task_id'}); 
    }); 
    this.route('subtasks', {path: '/subtasks/:task_id'}, function() { 
    this.route('subnew', {path: '/subnew/:task_id'}); 
    this.route('subedit', {path: '/subedit/:subtask_id'}); 
    }); 
}); 

export default Router; 

您已经定义task_id为子任务信息的动态段。所以你需要从子任务的模型钩子中的params参数中提取它。然后从模型钩子返回task_id

import Ember from 'ember'; 

const { 
    RSVP 
} = Ember; 

export default Ember.Route.extend({ 
    model(params){ 
     return RSVP.hash({ 
      subtasks: this.store.findAll('subtask'), 
      taskId: params.taskId 
     }); 
    } 
}); 

在此之后,您可以访问它在subtask.hbs这样的:

{{model.taskId}}