javascript 动态 ng-init 变量 - Angularjs
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18031560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamic ng-init variable - Angularjs
提问by shajin
.coffee
。咖啡
@FooCtrl = ->
$scope.products = Product.query()
.html
.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?
我想这样做。但是ng-init='images_{{product.id}}'
正在抛出一些异常。对此有任何补救措施或替代解决方案吗?
回答by Chandermani
The way you are doing may not work as ng-init take standard Javascript expression so {{}}
would not work.
您正在做的方式可能无法正常工作,因为 ng-init 采用标准 Javascript 表达式,因此{{}}
无法正常工作。
Since javascript objects are just a key-value collection. You need to access dynamic properties using []
notation instead on .
notation.
由于 javascript 对象只是一个键值集合。您需要使用[]
符号而不是.
符号来访问动态属性。
So this
所以这
<div ng-init='images_{{product.id}} = product.images >
<div ng-init='images_{{product.id}} = product.images >
becomes
变成
<div ng-init='this["images_"+this.product.id] = product.images'>
<div ng-init='this["images_"+this.product.id] = product.images'>
See thisfiddle i created
看到我创建的这个小提琴