2012-12-18 117 views
0

我是KnockoutJS新手。KnockoutJS嵌套列表

我有一个视图写在下面,并且在运行时无法看到每个类别的categoryVariables。 你可以看一看并说出这里有什么问题吗?

感谢您的帮助。

我的代码视图:

<table class="table"> 
    <thead> 
    </thead> 
    <tbody data-bind="foreach: categories"> 
     <tr> 
      <td data-bind="text: Name"> 
       <table> 
        <tbody data-bind="foreach: categoryVariables"> 
         <tr> 
          <td data-bind="text: Name"></td> 
         </tr> 
        </tbody> 
       </table> 
      </td> 
      <td><button data-bind='click: $root.addCategoryVariable'>Add a category variable</button></td> 
     </tr> 
    </tbody> 
</table> 

<button data-bind='click: addCategory'>Add a category</button> 

<script type="text/javascript"> 

    var resumeDataViewModel; 

    function Category(data) { 
     var self = this; 

     self.ID = data.ID; 
     self.Name = data.Name; 

     self.categoryVariables = ko.observableArray([ 
      new CategoryVariable({ID: '1', Name: 'asd'}) 
     ]); 
    } 

    function CategoryVariable(data) { 
     var self = this; 

     self.ID = data.ID; 
     self.Name = data.Name; 
    } 

    function ResumeDataViewModel() { 
     var self = this; 

     self.categories = ko.observableArray([ 
      new Category({ID: '1', Name : 'Contact', Category: {ID: '1', Name: 'gfdg'}}), 
      new Category({ID: '2', Name : 'Education', Category: {ID: '2', Name: 'asdasd'}}) 
     ]); 

     self.addCategory = function(){ 
      self.categories.push(new Category({ 
       Name: "sa d" 
      })); 
     } 

     self.addCategoryVariable = function (category) { 
      category.categoryVariables.push(new CategoryVariable({ 
       Name: 'asd' 
      })); 
     } 
    } 

    ko.applyBindings(resumeDataViewModel = new ResumeDataViewModel()); 
</script> 

寻找你的答复。非常感谢。

回答

3

你的问题是与文本的绑定:名称,然后将表添加到相同的TD。我已经将categoryVariables的表移动到单独的TD上,并且它工作正常。

由于您绑定了TD的文本,因此Ko的数据绑定将覆盖您在其中的任何其他内容,并仅设置可观察对象的文本。 如果您正在查看不同的UI布局,请相应地更改您的HTML,但请牢记上述内容。

另请检查KO文档中关于无菌容器绑定和绑定的使用。这些可以帮助您创建更好的HTML布局。

检查此琴:http://jsfiddle.net/7BNQy/

修改HTML:

<table class="table"> 
<thead> 
</thead> 
<tbody data-bind="foreach: categories"> 
    <tr> 
     <td data-bind="text: Name"> 

     </td> 
     <td> 
      <table> 
       <tbody data-bind="foreach: categoryVariables"> 
        <tr> 
         <td data-bind="text: Name"></td> 
        </tr> 
       </tbody> 
     </table></td> 
     <td><button data-bind='click: $root.addCategoryVariable'>Add a category variable</button></td> 
    </tr> 
</tbody> 
</table> 

<button data-bind='click: addCategory'>Add a category</button> 
+0

非常感谢你。你的回复将有助于我的KnockoutJS未来。再次感谢。 –