gpt4 book ai didi

javascript - Angular $viewValue 未反射(reflect)在更改事件的文本框中

转载 作者:行者123 更新时间:2023-12-03 04:47:06 28 4
gpt4 key购买 nike

我正在尝试实现 INR(印度卢比)到 USD(美元)的货币转换器。 View 应始终显示以 INR 为单位的值。但该模型应保存美元值(value)。

为此,我实现了一个用于输入的文本框。输入始终以 INR 为单位。

我正在使用 ngModel 的 $viewValue 和 $modelValue 属性来处理我的问题。

我遇到了一种情况,货币是在某些事件的后台计算的。例如。如果货币在模型中存储为 1 美元。在应用程序中的某些事件中,它会更改为 2 美元。在这种情况下,我的 View 显示以美元为单位的值(在本例中为 2 美元),并且仅当我关注文本框时,该值才会以 INR 为单位显示(如 126 INR)。

$viewValue 未在更改事件的文本框中显示。

请帮助我。

.directive('usdInrInput', function($filter, $timeout) {
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {

function conversionFunction() {
modelCtrl.$viewValue = modelCtrl.$modelValue * 63;
modelCtrl.$render();
}
element.bind("focus", function(e) {
$timeout(function() {
conversionFunction();
}, 0);
});
element.bind("change", function(e) {
$timeout(function() {
conversionFunction();
}, 0);
});
modelCtrl.$parsers.push(function(inputValue) {
var changedOutput = parseInt(inputValue) / 63;
modelCtrl.$setViewValue(parseInt(inputValue));
modelCtrl.$render();
return parseInt(changedOutput);
});
}
};
})

最佳答案

您应该使用 scope.$watch 监视模型值的变化,如下所示:

scope.$watch(function() {
return modelCtrl.$modelValue;
}, function(val) {
conversionFunction();
});
  • 使用美元汇率常量,以便在发生变化时可以在一处进行修改。

  • 使用 $evalAsync 而不是 $timeout(function(){},0)

引用evalAsync vs timeout

演示

出于演示目的,我故意使用 $timeout 在 2 秒后更改了模型值。

angular
.module('myApp', []);
angular
.module('myApp')
.controller('MyController', MyController)
.directive('usdInrInput', usdInrInput);
MyController.$inject = ['$scope', '$timeout'];

function MyController($scope, $timeout) {
$scope.inr = 630;
$timeout(function() {
$scope.inr = 10;
}, 2000);
}

usdInrInput.$inject = ['$filter', '$timeout'];

function usdInrInput($filter, $timeout) {
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
var cRate = 63;
scope.$watch(function() {
return modelCtrl.$modelValue;
}, function(val) {
conversionFunction();
});

function conversionFunction() {
modelCtrl.$viewValue = modelCtrl.$modelValue * cRate;
modelCtrl.$render();
}
element.bind("focus", function(e) {
scope.$evalAsync(function() {
conversionFunction();
});
});
element.bind("change", function(e) {
scope.$evalAsync(function() {
conversionFunction();
});
});
modelCtrl.$parsers.push(function(inputValue) {
var changedOutput = parseInt(inputValue) / cRate;
modelCtrl.$setViewValue(changedOutput);
modelCtrl.$render();
return changedOutput;
});
}
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>

<div ng-app="myApp" ng-controller="MyController as MC">

<input type="text" ng-model="inr" usd-inr-input> {{inr}}
</div>

关于javascript - Angular $viewValue 未反射(reflect)在更改事件的文本框中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42825677/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com