2013-06-26 34 views
0

我想使用Knockout将对象映射到表格。首先,我会告诉你我的对象:KnockoutJS - 根据变量将对象绑定到表格

function tableViewModel() { 
    var self = this;  
    self.data = ko.observableArray(); 

self.data.push(
    { 
     "Warnings": { 
      "numbers": 30, 
      "content": [ 
       { 
       "number" : 3001, 
       "description" : "There may be a problem with the device you are using if you use the default profile" 
       }, 
       { 
       "number" : 3002, 
       "description" : "There may be a problem with the device you are using if you don't use the default profile" 
       } 
      ] 
     }, 
     "Errors": { 
      "numbers": 20, 
      "content": [ 
       { 
       "number": 1000, 
       "description": "No network is loaded" 
       }, 
       { 
       "number": 1000, 
       "description": "No network is loaded" 
       } 
      ] 
     } 
    } 
); 

    self.dataTitle = ko.observable("Warnings")    
} 

ko.applyBindings(tableViewModel()); 

该对象包含两个“对象”,警告和错误。我希望能够在淘汰赛中根据变量(在这种情况下,在变量dataTitle上)仅显示警告的内容(如果dataTitle ==“Warnings”)或错误的内容。

基本上,我希望它查找与dataTitle的内容对应的对象。

我想实现这样的事情,但oviously它不工作:

<table class="table table-hover" data-bind="foreach: data"> 
    <thead> 
     <tr> 
      <th style="width:100px">Numero</th> 
      <th>Description</th> 
     </tr> 
    </thead> 
    <tbody data-bind="foreach: data[dataTitle].content"> <!-- This line is not giving expected results --> 
     <tr> 
      <td data-bind="text: $data.number"></td> 
      <td data-bind="text: $data.description"></td> 
     </tr> 
    </tbody> 
</table> 

这里有一个代表的jsfiddle问题:http://jsfiddle.net/etiennenoel/bqcMR/

我的问题是:有没有办法使用KnockoutJS来做那件事还是需要多少?

回答

1

好吧,你可以把表成模板,如果你只希望有它在你的页面一次,但这个工程:

<tbody data-bind="visible: $root.dataTitle() === 'Warnings', foreach: $data.Warnings.content"> 
    <tr> 
     <td data-bind="text: number"></td> 
     <td data-bind="text: description"></td> 
    </tr> 
</tbody> 
<tbody data-bind="visible: $root.dataTitle() === 'Errors', foreach: $data.Errors.content"> 
    <tr> 
     <td data-bind="text: number"></td> 
     <td data-bind="text: description"></td> 
    </tr> 
</tbody> 

你已经基本上得到了一个表中的每个部分,只显示你想要的那个。

我对视图模型做了一些其他的改变,同时试图让这个工作,我不知道他们是否需要。请参阅fiddle

+0

挂上,这是不是很工作... –

+0

希望,我想不能分裂我的数据。如果这是不可能的,那么我将不得不应付它。 – CoachNono

+0

试试这个,它在更新的小提琴中工作。 –