0

Can I use ng-repeat and $index to set a model property dynamically?

I'm trying to do something like this:

<div ng-repeat="x in [].constructor(10) track by $index">
  <input ng-model="model.prop{{$index}}">    
</div>

And I want my model to end up like this (i.e. so these properties don't exist in the controller code, I want them to be dynamically added):

{
  "prop0": "val",
  "prop1": "val",
  "prop2": "val",
  "prop3": "val",
  "prop4": "val",
...
  "prop10": "val"

  "otherProperty": "xxx"
}

I don't want the properties to be an array and I need to do this without changes to the controller.

Thanks

Sun
  • 4,458
  • 14
  • 66
  • 108

2 Answers2

0

You can iterate object (key, value) in directive ng-repeat

Controller

$scope.props = {
  "prop0": "val",
  "prop1": "val",
  "prop2": "val",
  "prop3": "val",
  "prop4": "val",
...
  "prop10": "val"
}

HTML:

<div ng-repeat="(key, value) in props">
  <input ng-model="props[key]">    
</div>

In some cases you should avoid using track by $index please check Tracking and Duplicates in AngularJs doc and When not to use 'track by $index' in an AngularJS ng-repeat? on StackOverflow.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Abinesh Joyel
  • 2,043
  • 2
  • 13
  • 18
0

Sorted, I did this:

<div ng-repeat="x in [].constructor(10) track by $index">
  <input ng-model="model.['prop' + ($index)]">    
</div>
Sun
  • 4,458
  • 14
  • 66
  • 108
  • this worked for you? did you have to create some sort of directive? id love to see your controller. do you think you can explain your solution? – chadlei Dec 02 '21 at 01:14