简体   繁体   中英

angularjs set default value ng-model using value from another ng-model

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>

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM