如何将 html 添加到 emberjs 模板?

How do I add html to an emberjs template?

如果我从以下开始:

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

谢谢。

您想将要添加的 html 添加到模板中,但在循环结构中 - 在本例中为 {{#each}}。该循环将遍历您跟踪的 children 数组。每当您将对象添加到 children 数组时,Ember 将重新呈现循环,因此 add 会为您重新呈现 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>

您想处理 addChild 操作,以便它向您的 children 数组添加一个对象。您可以像这样在控制器中执行此操作:

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