3

.coffee

@FooCtrl = ->
  $scope.products = Product.query()

.html

<div ng-repeat='product in products'>
  <div ng-init='images_{{product.id}} = product.images' >
    <div class='slideshow' ng-repeat='pic in images_{{product.id}}'>
       <img ng-src='{{pic.url}}' />
    </div>
</div>

I wanna do like this.But ng-init='images_{{product.id}}' is throwing some exception.Any remedy or alternate solution for this?

1 Answer 1

17

The way you are doing may not work as ng-init take standard Javascript expression so {{}} would not work.

Since javascript objects are just a key-value collection. You need to access dynamic properties using [] notation instead on . notation.

So this

<div ng-init='images_{{product.id}} = product.images >

becomes

<div ng-init='this["images_"+this.product.id] = product.images'>

See this fiddle i created

Sign up to request clarification or add additional context in comments.

3 Comments

The newly created variable can't be accessible in angular controller. $scope.images_x is undefined. any solution???
@Chandermani it somehow worked. But how? Why this works and where from did you get the knowledge, that this solution will fit? Browsing through Angular docs I saw that it frequently lacks thorough explanations for some problems - examples are too easy; there are too less more advanced examples. Does it mean, I'm forced to browse through Angular source code to come by myself with such solution, you provided?
This is not a common use case. Expressions in Angular are evaluated in context of scope. And it seems this during expression evaluation points to the scope object. Rest is our understanding of JavaScript which we use to access dynamic variable using []. It was more of hit and trial and a thought around what would this point to when evaluation happen. I did not look at source code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.