I have successfully implemented this code in IE 11, but now we are looking to transition away from IE11 and address some of the issues that have arisen.
<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 retrieve the input value from the element because if the input is a number type with non-numeric values, 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;
}
}
};
}]);
This functionality allows you to enter an expression like 100*2 into the input field, which will then evaluate the expression and display the result. However, when testing this in Edge or Chrome, the elem[0].value does not contain a value.
I have attempted to retrieve the value using other methods such as elem.val() and attr.evaluateInput, but these either return null or the name of the model. It seems like the ng-model has not been set when this directive is triggered.
Any assistance or guidance in the right direction would be highly appreciated.