Do I need 2 ng-models for this?

63 views Asked by At

I'm trying to create a form where the input fields are populated with values from an array, but the form is saved into a different array.

For example the fields would be populated from this array

{
  "organisation": [
    {
      "OrgID": 1234,
      "OrgName": "Organisation one"
    },
    {
      "OrgID": 4567,
      "OrgName": "Organisation two"
    },
    {
      "OrgID": 9876,
      "OrgName": "Organisation three"
    }
  ]
}

The input field I am using is this

<input type="text" ng-model="formData.organisations[organisation.OrgID].name" id="{{organisation.OrgName}}" ng-value="organisation.OrgName"/>

So this should show the organisation name from the 'organisation' array, the user should be able to edit the field, and value should be pushed into a new array called 'formData'. Is this possible in Angular?

2

There are 2 answers

0
dfsq On BEST ANSWER

You will be able to achieve this with the help of ngInit like this:

<input type="text" 
    ng-init="formData.organisations[organisation.OrgID].name = organisation.OrgName"
    ng-model="formData.organisations[organisation.OrgID].name" 
    id="{{organisation.OrgName}}" />

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

0
maged On

In your controller initialise formData.organisations to have all the information you need from the organisations array, along the lines of:

$scope.formData.organisations = angular.copy($scope.organisations);