Avi A
Avi A

Reputation: 69

How to define a ng-model dynamically when using $index

I wan't to use $index in order to create a new $scope variable:

    <div ng-repeat="i in items track by $index">   
            <input autocomplete="off" type="text" 
             ng-model="myVariableName{{$index}}" >
            ....

I wan't to declare the variable: myVariableName0, myVariableName1, etc...

Upvotes: 1

Views: 49

Answers (3)

Slava Utesinov
Slava Utesinov

Reputation: 13488

angular.module('app', [])
input,
span {
  display: block
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='app'>
  <input type='text' ng-repeat='temp in [0,1,2,3]' ng-model='$parent["myVariableName" + $index]' />
  <span>0: {{myVariableName0}}</span>
  <span>1: {{myVariableName1}}</span>
  <span>2: {{myVariableName2}}</span>
  <span>3: {{myVariableName3}}</span>
</div>

Upvotes: 0

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41387

In the controller declare empty object

$scope.myVariableName = {};

And in the template assign the model value as a property of an object.

ng-model="myVariableName[$index]"

Upvotes: 1

Suren Srapyan
Suren Srapyan

Reputation: 68635

Instead of doing this you can have an array, and each item of that array can refer to the current ng-model via ng-model="myVariableName[$index]"

Upvotes: 0

Related Questions