Reputation: 992
I have declared and initialized few Scope variables and want to access them dynamically, but when I try to access a variable from html file, that variable is treated as a string.
JS Code-
$scope.abc3txt = "Hello";
$scope.abc2txt = "hello everyone";
$scope.abc1txt = "hello 123";
There is a number with every variable like 3,2,1 between abc"number"text.
I want to access the variable value according to the number in my html file.
HTML code-
<h4>{{abc+a.status+txt}}</h4>
a.status has some value like 1,2 or 3.
This prints like "abc3txt" in html, instead of returning the initialised value of "$scope.abc3txt" variable.
Please someone help..
Upvotes: 0
Views: 975
Reputation: 17711
You absolutely shouln't use variables namese that way, in javascript...
Consider using arrays...
Something like this should help:
In the controller:
$scope.a = {};
$scope.a.status = 2;
$scope.abctxt = [ "hello 123", "hello everyone", "Hello" ];
And, in the template:
<h4>{{ abctxt[a.status - 1] }}</h4>
Upvotes: 3
Reputation: 429
I don't know if it can be done with $scope
directly. A way would be to save those values in an object:
$scope.values = {
abc3txt: "Hello",
abc2txt: "hello everyone",
abc1txt: "hello 123"
};
And in you view you could access them like this:
{{values['abc' + a.status + 'txt']}}
EDIT: The best alternative would be to use the controllerAs syntax. Suppose you have in controller:
var vm = this;
vm.abc3txt = "Hello";
vm.abc2txt = "hello everyone";
vm.abc1txt = "hello 123";
Then in your view:
{{vm['abc' + a.status + 'txt']}}
Upvotes: 3
Reputation: 3675
Dynamic generation of variable names in the way you are seeking is, in all possible perspective, a very, very, SUPER-VERY bad practice, and this regardless of the support (or lack of it) a language may have. Having said that, arrays is the right way to go.
Upvotes: 3