I would like to ask you if you can give me a hand on this.
I have created a jsfiddle with my problem here. I need to generate dynamically some inputs with ng-model in a ng-repeater using the way ng-model="my_{{$index}}".
In jsfiddle you can see that everything it's working fine until I try to generate it dynamically.
The html would be:
<div ng-app>
<div ng-controller="MainCtrl">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td>
<select ng-model="selectedQuery"
ng-options="q.name for q in queryList" >
<option title="---Select Query---" value="">---Select Query---</option>
</select>
</td>
</tr>
<tr ng-repeat="param in parameters">
<td>{{param}}:</td>
<td><input type="text" ng-model="field_X" />field_{{$index}}</td>
</tr>
</table>
<div>
<div>
And the javascript...
function MainCtrl($scope) {
$scope.queryList = [
{ name: 'Check Users', fields: [ "Name", "Id"] },
{ name: 'Audit Report', fields: [] },
{ name: 'Bounce Back Report', fields: [ "Date"] }
];
$scope.$watch('selectedQuery', function (newVal, oldVal) {
$scope.parameters = $scope.selectedQuery.fields;
});
}
Can you give me any idea?
Thanks a lot.
Does it solve your problem?
And in your controller:
Fiddle
I did elaborate my answer from pkozlowski's and try to generate a dynamic form, with dynamic ng-model:
But first, we need to define the 'human' scope inside our controller
And then, on submission we will have the data like this (depending on how much field is generated):
It's pretty straightforward and I hope my answer helps.
Is there a reason to generate those field names? Can you treat each field as an object with name and value instead of a string name? (FIDDLE)
And just repeat off of
selectedQuery.fields
:Beterraba's answer was very helpful for me. However, when I had to migrate the solution to Typescript it wouldn't behave for me. Here is what I did instead. I expanded the individual parameters (fields on the queryList in your example) into full objects that included a "value" field. I then bound to the "value" field and it worked great!
Originally you had:
I changed it to something like this:
...and bound to the 'Value' sub-field.
Here is my Typescript if you care.
In the html:
In the sproc-param directive that uses Angular Material. See where I bind the ng-model to param.Value:
What you could do is to create an object on a scope (say,
values
) and bind to the properties of this object like so:Here is a jsFiddle illustrating the complete solution: http://jsfiddle.net/KjsWL/