0

I would like to pass the value of an ng-model that the user sets in a another form field select options to another ng-model as initial value in the same form.
In this example, I want the ng-init value of myModel.fieldB to be the value myModel.fieldA.subfield, this is successfully evaluating in the value of the span element, but not in the ng-model for myModel.fieldB, meaning that nothing is happening in ng-init="myModel.fieldB = myModel.fieldA.subfield".
However when I pass string literal values, it works, for example ng-init="myModel.fieldB = 'some example'"

<span class="form-group" ng-model="myModel.fieldB" ng-init="myModel.fieldB = myModel.fieldA.subfield">{{myModel.fieldA.subfield}</span>
passion
  • 1,000
  • 6
  • 20
  • 47

2 Answers2

1

Why don't you simply make use of ng-change directive for your select input and assign the value of myModel.fieldA.subfield to the myModel.fieldB ?

Just like this:

ng-change="assignValue(myModel.fieldA.subfield)"

Then:

$scope.assignValue = function(val) {
    if (val) {
      $scope.myModel.fieldB = val;
    }
  }

Here's a working plunker

korteee
  • 2,640
  • 2
  • 18
  • 24
1

that's because when you pass the literal value it's constant and not going to change but when you pass the variable value like this ng-init="myModel.fieldB = myModel.fieldA.subfield" (myModel.fieldB) it will be set only once at the creation time of this element with whatever value inside (myModel.fieldA.subfield), so to overcome this you can use ng-change on the select element as below:

<select data-ng-model="myModel.fieldB" ng-change="myModel.fieldA.subfield = myModel.fieldB">
   <option value="option1">option1</option>
   <option value="option1">option1</option>
</select>
<span class="form-group">{{myModel.fieldA.subfield}}</span>
Mostafa Omar
  • 167
  • 2
  • 6