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>
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>