Reputation: 328
Here is the situation. I have two tables:
MSSQL
Products
ProductId | ProductName
__________|____________
1 | iPhone5
2 | iPhone6
3 | iPhone6s
Images
Id | ImagePath | ProductId
___|__________________|___________
1 | /images/231.jpg | 2
2 | /images/432.jpg | 2
3 | /images/111.jpg | 1
My knockout:
<div data-bind="foreach: Products">
<div data-bind="text: ProductName">
<div data-bind="foreach: Images>
<img data-bind="attr:{src: ImagePath}" />
</div>
</div>
</div>
So I want to get all images of each Product. Should I merge two table into one Json, and how do I get id from outer loop? Thanks!
p.s. i am using asp.net if it helps.
Upvotes: 1
Views: 410
Reputation: 53958
You could try something like the following. Based on the following snippet, I suppose that the products
would be feed from an ajax call. That being said you have to change correspondingly this part. Essentially, what you ajax call would return would be an array of products and each product should have at least a name and an array of images (an empty array if none image exists for this product). Apparently, you could add any other information you want to your response. So you have to tweak a bit the functions that have been declared below, Image
and Product
.
var Image = function(name){
this.name = name;
};
var Product = function(name, images){
this.name = name;
this.images = images;
};
var viewModel = {
products: [
new Product("iPhone5", [new Image("/images/111.jpg")]),
new Product("iPhone6", [new Image("/images/231.jpg"),new Image("/images/432.jpg")]),
new Product("iPhone6s", [new Image("/images/444.jpg")])
]
};
ko.applyBindings(viewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div data-bind="foreach: products">
<div data-bind="text: name"> </div>
<ul data-bind="foreach: images">
<li data-bind="text: name"></li>
</ul>
</div>
Upvotes: 1
Reputation: 360
You can use $parent
to access one scope level up. So, from your inner loop you can use parent to access the current item being looped on in your Products
Upvotes: 1