1

I am trying to update a $scope variable:

ex:

$scope.variable_1
$scope.variable_2
...

I would like to update it this way:

for (i=0; i<2; i++) {    
  $scope.variable_$i = 1;
}

What I need is to get access to the "$scope.variable_1" using the index "i" in each iteration.

any suggestion? Thanks in advance.

2

1 Answer 1

2

In javascript you can access variables by their name :

for (i=0; i<2; i++) {    
  $scope['variable_'+i] = 1;
}

See : Dynamically access object property using variable

Also, accessing properties this way should be avoided if you can use an array instead.

Sign up to request clarification or add additional context in comments.

2 Comments

Correct answer but I don't think one should use variables in such cases! May be Array is the way to go..
Totally agree, added note about this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.