Reputation: 529
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>
Upvotes: 0
Views: 1189
Reputation: 3820
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;
}
}
Upvotes: 2