[英]AngularJS: Name a variable using another's variable value
我是AngularJS的新手,我仍在探索它的可能性。 当前,我遇到了这个问题:如何使用他人的变量值命名变量?
例如,我的控制器中有以下内容:
$scope.item_foo = 'Foo';
$scope.item_bar = 'Bar';
我可以这样访问值:
{{item_foo}}
{{item_bar}}
到目前为止一切顺利,但是现在我想动态显示它们。 我有一个带有'foo'和'bar'的对象,并使用ngRepeat对其进行循环。 我该怎么做:
{{item_{{variable_with_value_foo_or_bar}}}} // should print Foo and Bar
感谢您的帮助!
似乎最好使用一个对象来存储数据,而不是使用$scope
级别的东西……:
$scope.item = {foo: 'Foo', bar: 'Bar'};
// ...
$scope.variable_with_value_foo_or_bar = 'foo';
然后使用:
{{item[variable_with_value_foo_or_bar]}}
在模板中, this
是指当前范围,因此您可以执行以下操作:
{{ this[ 'item_' + variable_with_value_foo_or_bar ] }}
可能有更好的方法来执行您要执行的操作,但是希望这可以回答您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.