[英]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. 我想将用户在另一个表单字段中设置的ng-model的值传递给另一个ng-model,将其作为相同表单的初始值。
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"
. 在此示例中,我希望
myModel.fieldB
的ng-init值为myModel.fieldA.subfield
,这是在span元素的值中成功评估的,但在myModel.fieldB
的ng-model中未成功评估,这意味着ng-init="myModel.fieldB = myModel.fieldA.subfield"
中没有任何ng-init="myModel.fieldB = myModel.fieldA.subfield"
。
However when I pass string literal values, it works, for example ng-init="myModel.fieldB = 'some 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
? 为什么不简单地将
ng-change
指令用于选择input
并将myModel.fieldA.subfield
的值分配给myModel.fieldB
呢?
Just like this: 像这样:
ng-change="assignValue(myModel.fieldA.subfield)"
Then: 然后:
$scope.assignValue = function(val) {
if (val) {
$scope.myModel.fieldB = val;
}
}
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: 这是因为当您传递文字值时,它是常量并且不会改变,但是当您传递变量值时,例如
ng-init="myModel.fieldB = myModel.fieldA.subfield"
(myModel.fieldB),它将仅被设置一次在此元素具有任何内部值(myModel.fieldA.subfield) 的创建时 ,因此要克服此问题,可以对select元素使用ng-change,如下所示:
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.