2015-03-08 166 views
0

如果我先從以下內容:如何將html添加到emberjs模板?

<script type="text/x-handlebars" id="Parent"> 
    <p>Name: {{input type="text" value=name}}</p> 
    <button {{action 'addChild'}}>Add Child</button> 
</script> 

我想按一下按鈕,產生如下:

<script type="text/x-handlebars" id="Parent"> 
    <p>Name: {{input type="text" value=name}}</p> 
    <p>Child1 Name: {{input type="text" value=child1_name}}</p> 
    ... 
    ... 
    ... 
    <p>Childn Name: {{input type="text" value=childn_name}}</p> 
    <button {{action 'addChild'}}>Add Child</button> 
</script> 

感謝。

回答

1

你想把你希望加入到模板中的HTML,而是一個循環構造內 - 在這種情況下{{#each}}。循環將迭代你追蹤的children數組。無論何時您向children陣列添加對象,Ember都會重新渲染循環,因此會爲您添加 html。您的模板將是這樣的:

<script type="text/x-handlebars"> 
    <p>Name: {{input type="text" value=name}}</p> 

    {{#each child in children}} 
    <p>{{child.name}}: {{input type="text" value=child.value}}</p> 
    {{/each}} 

    <button {{action 'addChild'}}>Add Child</button> 
    </script> 

你想的那麼它增加了一個對象插入到children陣列來處理addChild行動。您可以在控制器做到這一點,像這樣:

App.ApplicationController = Ember.Controller.extend({ 
    name: 'Parent Name', 
    children: [], 

    actions: { 
    addChild: function() { 
     var children = this.get('children'); 
     var id = children.length + 1; 
     children.addObject({ 
     name: 'Child Name ' + id, 
     value: id 
     }); 
    } 
    } 

}); 

這裏是一個功能JSBin,你可以體驗:http://emberjs.jsbin.com/gujomizici/1/edit?html,js,output

+0

感謝傑米!我的代碼開始看起來像你想出的,但我將改變我的代碼以符合你的解決方案。 – user2517182 2015-03-09 21:45:15