0

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>
1
  • 4
    Why don't you make it an array? Commented Jun 23, 2017 at 14:16

1 Answer 1

2

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;
  }
}

JSFIDDLE

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

5 Comments

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.
Sorry just remove the _ on controller and view. But the approach is identical... As updated on above answer.
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!
Its just a way to set a scope variabele with the loop counter on a dynamic way. Not sure if this helps you?
@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 ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.