Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm new to AngularJS and I'm still exploring its possibilities. Currently I'm stuck with this problem: How can I name a variable using another's variable value?

For example I have something like this in my controller:

    $scope.item_foo = 'Foo';
    $scope.item_bar = 'Bar';

I can access the values with this:

    {{item_foo}}
    {{item_bar}}

So far so good, but now I want to display them dynamically. I have an object with 'foo' and 'bar' and I loop it with ngRepeat. How can I do something like that:

    {{item_{{variable_with_value_foo_or_bar}}}} // should print Foo and Bar

Thank you for any of your help!

share|improve this question
add comment

2 Answers 2

up vote 1 down vote accepted

Within your template, this refers to the current scope, so you can do:

{{ this[ 'item_' + variable_with_value_foo_or_bar ] }}

There are probably better ways to perform what you're trying to do, but hopefully this answers your question.

share|improve this answer
    
Thank you so much! This is exactly the solution I was looking for. –  ohh2ahh Mar 21 at 19:49
add comment

It seems like it would be better to use an object to store the data, rather than a bunch of things at the $scope level...:

$scope.item = {foo: 'Foo', bar: 'Bar'};
// ...
$scope.variable_with_value_foo_or_bar = 'foo';

Then access with:

{{item[variable_with_value_foo_or_bar]}}
share|improve this answer
    
Thank you very much for your answer. Actually, my problem is not as easy as I wrote. It has a specific reason why I'm doing this. I'm sure it's not "best practice", but I'm still learning :) –  ohh2ahh Mar 21 at 19:48
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.