SWeC SWeC - 2 months ago 10
AngularJS Question

JS/AngularJS: Dynamically create variable name

I need to declare variable with name based on the same root but with different names as in the below example:

$scope.form1 = //something
$scope.form2 = //something


the scope is to create dynamically this name using another variable. Something like this:

$scope.form[count] = //something


but the result should be something like form1 and not form.1

thanks to all!

Answer

You just need to make a string with the full name of the property.

$scope["form" + count]

… although a better approach would probably be to not have property names that differ only by a number in a first place. Use one property with an array as its value instead.

$scope.forms = [something, something];
$scope.forms[count];