sajalsuraj sajalsuraj - 1 year ago 34
HTML Question

$scope variable is treated as string - AngularJs

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-


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..

Answer Source

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']}}