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>

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.