【发布时间】:2021-09-13 09:40:44
【问题描述】:
这是我目前在 IE 11 中实现和工作的内容,现在我们正试图摆脱 IE11 并修复一些弹出的问题。
<input type="number" evaluate-input="model.personalNumber" ng-model="model.personalNumber" maxlength="50" ng-change="..." ng-blur="..." />
angular.module("myApp")
.directive("evaluateInput", [
function () {
return {
restrict: "A",
replace: true,
scope: {
evaluateInput: "="
},
link: function ($scope, elem, attrs, ctrl) {
/* Need to grab the input from the element because if the input is a number type and it has non-numeric values then the model will be empty. */
var inputValue;
elem.bind("keyup", function (e) {
inputValue = elem[0].value;
if (e.keyCode === 13) {
$scope.$apply(function () {
calculateFormula();
});
}
})
elem.bind("blur change", function (e) {
inputValue = elem[0].value;
$scope.$apply(function () {
calculateFormula();
});
})
/* Uses the javascript eval function but catches and swallows any errors and returns null */
function calculateFormula() {
var result = null;
try {
result = eval(inputValue);
result = Number(result.toFixed(2));
}
catch (e) {
// No need to generate an error on invalid input.
// Just leave the result as null
}
$scope.ngModel = result;
}
}
};
}]);
它的工作方式是您可以在输入中键入像 100*2 这样的表达式,它会计算表达式并返回结果。在 Edge 或 Chrome 中运行时,elem[0].value 没有设置值。
我尝试使用其他方法获取值,例如 elem.val() 和 attr.evaluateInput,但这些方法要么返回 null,要么返回模型名称。当这个指令被命中时,好像还没有设置 ng-model。
任何正确方向的帮助或信息将不胜感激。
【问题讨论】:
-
你使用的是哪个版本的AngularJS?
-
@Julien 目前使用 v1.7.8
标签: javascript angularjs angularjs-directive