更新时间:2023-01-26 21:58:27
我觉得最简单,最快,最正确的解决办法是有一个标志来跟踪哪些领域正在被编辑,只允许从该领域的更新。
I think the simplest, fastest, and most correct solution is to have a flag to track which field is being edited, and only allow updates from that field.
您只需要使用 NG-变化
指令设置标志场上正在编辑中。
All you need is to use the ng-change
directive to set the flag on the field being edited.
code必要的修改:
Code changes necessary:
修改控制器看起来是这样的:
Modify the controller to look like this:
function TemperatureConverterCtrl($scope) {
// Keep track of who was last edited
$scope.edited = null;
$scope.markEdited = function(which) {
$scope.edited = which;
};
// Only edit if the correct field is being modified
$scope.$watch('fahrenheit', function(value) {
if($scope.edited == 'F') {
$scope.celsius = (value - 32) * 5.0/9.0;
}
});
$scope.$watch('celsius', function(value) {
if($scope.edited == 'C') {
$scope.fahrenheit = value * 9.0 / 5.0 + 32;
}
});
}
然后这个简单的指令添加到输入字段(使用˚F
或 C
如适用):
<input ... ng-change="markEdited('F')/>
现在仅领域正在键入在可改变的另一个。
Now only the field being typed in can change the other one.
如果您需要修改的能力,这些领域的之外的输入,你可以添加,看起来像这样的范围或控制器功能:
If you need the ability to modify these fields outside an input, you could add a scope or controller function that looks something like this:
$scope.setFahrenheit = function(val) {
$scope.edited = 'F';
$scope.fahrenheit = val;
}
然后摄氏度场将在接下来的$更新周期消化
Then the Celsius field will be updated on the next $digest cycle.
此溶液具有的额外code进行最低限度,消除了每个周期的多个更新的任何机会,并不会导致任何性能问题。
This solution has a bare minimum of extra code, eliminates any chance of multiple updates per cycle, and doesn't cause any performance issues.