I am trying to create dynamic scope variable in angular.I am using a loop to set the variable name as v1,v2,v3 but still no success. Any idea how achieve this ?
js
for (var i = 0; i < 4; i++) {
$scope.v_i='value'+i;
}
html
<div>{{v1}}</div>
<div>{{v2}}</div>
<div>{{v3}}</div>
asked Jun 23, 2017 at 14:15
query
5273 gold badges8 silver badges30 bronze badges
-
4Why don't you make it an array?Vivz– Vivz2017年06月23日 14:16:51 +00:00Commented Jun 23, 2017 at 14:16
1 Answer 1
You can use the $scope object as typeof Array.
But I would wrap them to a $scope object wrapper items.
See both approaches below.
VIEW
<div ng-app="app" ng-controller="MainController">
{{v0}}
<br/> {{v1}}
<br/> {{v2}}
<br/> {{v3}}
<br/>
<br/> {{items}}
<br/>
<br/>
<div ng-repeat="item in items">
{{item}}
</div>
</div>
CONTROLLER
angular
.module('app', [])
.controller('MainController', MainController)
function MainController($scope) {
$scope.items = {};
for (var i = 0; i < 4; i++) {
$scope['v' + i] = 'value' + i;
// or add to object wrapper
$scope.items['v' + i] = 'value' + i;
}
}
answered Jun 23, 2017 at 14:16
daan.desmedt
3,8201 gold badge22 silver badges33 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
Frank Modica
Given the HTML, looks like it would have to be
$scope['v' + i]. Also, saying you're using it as Array might be a bit misleading. You're using bracket notation on an object.daan.desmedt
Sorry just remove the
_ on controller and view. But the approach is identical... As updated on above answer.hiswendy
hi @daan.desmedt I'm having a similar issue and can you explain what
'value' + i is supposed to do? I'm not sure the purpose of that line. Thank you!daan.desmedt
Its just a way to set a scope variabele with the loop counter on a dynamic way. Not sure if this helps you?
Pranesh Janarthanan
@daan.desmedt How do i use a dynamic scope variable inside the template to invoke the simillar dynamic variable already generated. For example i have dynamic variable scope.v +i = 1122. Now i want to use a simillar dynamic variable inside the template with ng-repeat. Example {{v+$index}} , for this i am getting v1 instead of 1122 in UI. Can you help me ?
lang-js