Consider the following code:
class StoreController
constructor: ->
@products = gems
current_id = 0
for product in @products
if product.images?
for img in product.images
img.id = current_id
current_id += 1
gems = [
{
name: 'Dodecahedron'
images: [
{
full: "assets/img0.gif"
}
{
full: "assets/img1.gif"
}
]
}
{
name: 'Gemmy Gem'
}
{
name: 'Pentagonal Gem'
}
]
Is there a better way to write the nested for loops to check for product.images? without that if product.images? line?
EDIT: The accepted answer below does actually answer this question. However, I decided to change the way I am writing my code to use a custom filter instead.
In filter.js.coffee , I wrote the following:
filterMod = angular.module 'storeFilters', []
current_id = 0
filterMod.filter 'addIds', ->
return (items) ->
# avoid $rootScope:infdig
return items if !items? || items.processed
for img in items
img.id = current_id
current_id += 1
items.processed = true
return items
The HTML goes below, notice the use of addIds in the inner ng-repeat
<div ng-controller="StoreController as store">
<ul ng-repeat="product in store.products" class="list-group">
<li class="list-group-item">
<h3> {{product.name}} <em class="pull-right">{{product.price | currency }}</em></h3>
<div class="gallery">
<div ng-repeat="img in product.images | addIds ">
{{img.id}}
<img ng-src="{{img.full}}"/>
</div>
</div>
<p> {{product.description}}</p>
<button ng-show="product.canPurchase">Add to Cart</button>
</li>
</ul>
</div>
And for the sake of completeness, here goes app.js.coffee
app = angular.module 'store', ['storeFilters']
app.controller 'StoreController',
class StoreController
constructor: ->
@products = gems
gems = []