我有2个型号:

var ProductModel = function(productid, productname, producttypeid, productprice) {
  var self = this;
  self.ProductId = productid;
  self.ProductName = productname;
  self.ProductTypeId = producttypeid;
  self.ProductPrice = productprice;
}


var ProductTypeModel= function(producttypeid, producttypename) {
  var self = this;
  self.ProductTypeId = producttypeid;
  self.ProductTypeName = producttypename;
}

我在视图模型中使用它们:
var ProductViewModel = function() {
  var self = this;
  self.ProductList = ko.observableArray([]);
  self.ProductTypeList = ko.observableArray([]);

  //...init 2 array and some misc methods
}

在html文件中:

...
<table>
  <thead>
   <tr>
    <th>Id</th>
    <th>Type</th>
    <th>Name</th>
    <th>Price</th>
   </tr>
  </thead>
  <tbody data-bind="template: { name: 'row', foreach: ProductList }">
  </tbody>
</table>
...
<script id="row" type="html/template">
  <tr>
    <td data-bind="html: ProductId"></td>
    <td data-bind="html: ProductName"></td>
    <td data-bind="html: ProductTypeId"></td> <!-- I stuck here!!! -->
    <td data-bind="html: ProductPrice"></td>
  </tr>
</script>
...

我希望我的表显示ProductTypeName而不是ProductTypeId,但是我不能将ProductTypeId传递给任何函数来获取ProductTypeName。

最佳答案

var ProductViewModel = function() {
  var self = this;
  self.ProductList = ko.observableArray([]);
  self.ProductTypeList = ko.observableArray([]);

  //...init 2 array and some misc methods

  self.getProductTypeName = function (productTypeId) {
    var typeId = ko.unwrap(productTypeId),
        found = ko.utils.arrayFirst(self.ProductTypeList(), function (productType) {
           return ko.unwrap(productType.ProductTypeId) === typeId;
         });

    return found ? ko.unwrap(found.ProductTypeName) : null;
  };
};



<script id="row" type="html/template">
  <tr>
    <td data-bind="html: ProductId"></td>
    <td data-bind="html: ProductName"></td>
    <td data-bind="html: $root.getProductTypeName(ProductTypeId)"></td>
    <td data-bind="html: ProductPrice"></td>
  </tr>
</script>

09-16 12:41