我遇到的情况是,表单中有几个只读字段,就像其他字段一样来显示问题
您可以看到最后两个输入是只读
,它们是计算输入,其中总借记是通过$scope
上的totalDebit
函数计算的,并且总积分由 $scope
上的 totalCredit()
函数计算。问题是输入仅反射(reflect) ng-model 值,该值对于两个输入均为零,并且不从计算函数中获取值。简化的 Controller 是
app.controller('myController', ['$scope' ,function($scope){
$scope.credit = 0;
$scope.debit = 0;
$scope.debitSum = 0;
$scope.creditSum = 0;
$scope.totalCredit = function(){
return $scope.credit + 200; //just to show that it is calculated field
}
$scope.totalDebit = function(){
return $scope.debit + 200; //just to show that it is calculated field
}
}]);
如果您从只读输入中删除 ng-model
指令,它们将分别采用 totalDebit
和 totalCredit
函数的值。但我希望它们使用函数中的值,并更新 totalDebit
和 totalCredit
的 $scope
属性。这是plunker对于此代码
最佳答案
不应该在这里回答(为什么 ng-value 没有达到预期的效果):
ngValue
Binds the given expression to the value of
<option>
orinput[radio]
, so that when the element is selected, the ngModel of that element is set to the bound value.
这不是我们的情况......
Because, the
ngValue
is triggered on CHANGE. When we select radio or some option in the<select>
所以,ng-value
在这种情况下不是正确的设置。
我们可以这样调整:
<input name="totalDebit" value="{{totalDebit()}}" readonly="" />
<input name="totalCredit" value="{{totalCredit()}}" readonly="" />
关于angularjs - 从 ng-value 指令更新 ng-model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27675874/