Set ng-model name from Javascript

How can I set ng-model name from javascript?

HTML

<div ng-repeat="model in models">
    <input ng-model="?">
</div

JS

$scope.models= [
   {name: "modelOne"},
   {name: "modelTwo"},
   {name: "modelThree"}
];

Thanks a lot for answers.

Upvotes: 1

Views: 573

Answers (3)

dfsq
dfsq

Reputation: 193291

If your goal is to set up ngModel's by providing corresponding model names in variables, then you can still achieve it easily using old-good bracket notation.

So say you have variable $scope.modelName = 'modelOne' and you want to set up model so that you could use {{modelOne}} in template or $scope.modelOne in controller. It's very easy if you use bracket notation. In this case it will be $scope[$scope.modelName] = 'something'.

In you case, with ngRepeat there is a caveat because every iteration crates own child scope, so in order to set up model in proper scope, you need to use $parent reference to initial scope. So it will be:

<div ng-repeat="model in models">
    <input ng-model="this.$parent[model.name]">
</div>

So the key here is that this in ngWhatever always point to the scope object ($scope in controller). And since it's an object you just use bracket notation to access properties with variable name.

Demo: http://plnkr.co/edit/DGj3H5qiyHKOxbbdtK8p?p=preview

Upvotes: 1

floribon
floribon

Reputation: 19193

As simple as

<div ng-repeat="model in models">
  <input ng-model="model.name">
</div>

Explanations

The ng-repeat loops through your models array and will add a model item in your scope on each iterations. From the HTML inside that ng-repeat, you can use model as if you had put it in your $scope from the controller.

Feel free to read more documentation about ng-repeat

If that is not what you want

If $scope.models is supposed to be a list of property names, for instance you want to actually edit $scope.modelOne rather than the string modelOne itself (on second read I think that could be what you mean), you cannot do that directly but you can use an object in between, i.e. edit $scope.foo.modelOne rather than $scope.modelOne

<div ng-repeat="model in models">
  <input ng-model="foo[model.name]">
</div>

And in your controller have

$scope.foo = {
  'modelOne':   'some text',
  'modelTwo':   'some other text',
  'modelThree': 'hello world'
}

Upvotes: 4

forgivenson
forgivenson

Reputation: 4435

Based on the code in your question, it appears you want each <input> to have one of the models listed in your models array. If so, simply do:

<div ng-repeat="model in models">
    <input ng-model="model.name">
</div>

Upvotes: 1

Related Questions