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.
<div ng-repeat="model in models">
<input ng-model="model.name">
</div>
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 $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'
}
ng-repeat, you will have as many inputs as you have models. To change the second model you will edit the second input.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.
this tip, however that is still hacky since you need to use $parent. Here's a fork with the same spirit but using controller as: plnkr.co/edit/7R2d8mQXBxYvO4xilcfh?p=previewngRepeat you wouldn't need $parent. But in this case it's absolutely needed and it's allright. And using controller as is cheating to me, because :)
ng-model="model.name"should work...{{modelOne}}?