Dynamic ng-model name in AngularJS form

jdiver picture jdiver · Mar 18, 2014 · Viewed 30.4k times · Source

I have an AngularJS form where I'm using ng-repeat to build the fields of the form dynamically based on another selection. I'm trying to generate the model name dynamically and am running into problems.

<div class="form-group" ng-repeat="parameter in apiParameters">
  <label for="{{parameter.paramName}}" class="col-sm-2 control-label">{{parameter.paramTitle}}</label>
  <div class="col-sm-3">
    <input type="text" class="form-control" name="{{parameter.paramName}}" id="{{parameter.paramName}}" ng-model="formData.parameters.{{parameter.paramName}}" placeholder="{{parameter.paramTitle}}">
  </div>
</div>

What I need is it to eval to something like ng-model="formData.parameters.fooId" or ng-model="formData.parameters.barId"

The above results in an error: Error: [$parse:syntax] Syntax Error: Token '{' is an unexpected token at column 21 of the expression [formData.parameters.{{parameter.paramName}}] starting at [{{parameter.paramName}}].

In my controller I have:

$scope.formData = {};
$scope.formData = {
  settings:
  {
    apiEndpoint: '',
    method: 'get'
  },
  parameters: {}
};

I've also tried ng-model="formData.parameters.[parameter.paramName]" (based on this question How can I set a dynamic model name in AngularJS?), but that doesn't eval and fails to set the ng-model value. I'm not sure if what I'm trying to accomplish is even possible. I'm assuming I need to go through the controller to achieve what I want, but any help would be appreciated.

Answer

Sergey Moiseev picture Sergey Moiseev · Mar 18, 2014

You just need to use hash key as model:

<div class="form-group" ng-repeat="parameter in apiParameters">
  <label for="{{parameter.paramName}}" class="col-sm-2 control-label">{{parameter.paramTitle}}</label>
  <div class="col-sm-3">
    <input type="text" class="form-control" name="{{parameter.paramName}}" id="{{parameter.paramName}}" ng-model="formData.parameters[parameter.paramName]" placeholder="{{parameter.paramTitle}}">
  </div>
</div>

There is many other approaches, but this one are simpler than others.