Tips on how to retrieve the value of a number-type input within a custom attribute directive

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.

Answer №1

Your primary issue is related to the HTML5 constraint validation.

According to the AngularJS documentation:

When a non-number value is entered in the input, the browser will recognize it as an empty string. Consequently, the view, model values in ngModel, and subsequent scope value will also be empty strings.

To resolve this problem, you need to change your input type to text.

I have addressed this issue along with other minor mistakes in the updated example below:

const app = angular.module("myApp", []);

app.controller('TestCtrl', function() {

  const ctrl = this;

  ctrl.personalNumber = 2;
})

app.directive("evaluateInput", [
  function() {
    return {
      restrict: "A",
      scope: {
        ngModel: '='
      },
      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) {
            calculateFormula();
          }
        })

        elem.bind("blur change", function(e) {

          inputValue = elem[0].value;

          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;
        }

      }
    };

  }
]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="TestCtrl as model">

    <input type="text" evaluate-input ng-model="model.personalNumber" maxlength="50" />

    <div>
      {{model.personalNumber}}
    </div>

  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for updating an element in an array by using another element from a separate array

What is the objective? We have two arrays: orders and NewOrders We need to check for any orders with the same order_id in both arrays. If there is a match, we then compare the order status. If the order from the NewOrders array has a different status, w ...

Building a Laravel PHP application that dynamically generates a custom JSON object fetched from the database and passes it from PHP to

I am faced with the task of generating a custom JSON object by organizing data retrieved from PHP in my Controller. I have full control over what information goes where and in what specific order. To accomplish this, it seems like I will need to go throug ...

What is the best way to eliminate a blank array in JavaScript?

After countless hours of searching, I am reaching out for help with an issue that has me stumped. My Node.js application relies on JSON files for project configurations. Using the 'fs' module, I read the JSON file, parse it into a JavaScript obje ...

Unraveling the mystery: Retrieving event.target.value in a React component

Having trouble accessing the event.target.value from a React child Component, but not an HTML tag? In this scenario: the Button tag (React Component) cannot access event.target.value, while the button tag (HTML tag) can. import React from "react"; impor ...

I encountered an issue while constructing a React application. An error message popped up indicating: "Warning: Can't execute a React state update on a component that is not mounted"

Having difficulty pinpointing the source of the error message displayed below. Should I focus my investigation on the specific lines mentioned in the console, such as Toolbar.js:15? Is the console indicating that the error lies there? Additionally, what i ...

Add JSON elements to an array

Looking for help! {"Task": [Hours per Day],"Work": [11],"Eat": [6],"Commute": [4],"Sleep": [3]} Need to add these items to a jQuery array. I've attempted using JSON.parse without success. Typically, I can push parameters as follows: MyArr.push([& ...

Displaying the second image twice in a jQuery image slider

When attempting to implement a slider on my website, I encountered an issue where the second image appears twice in a row before the slider starts working as expected. I'm struggling to figure out why this is happening. Here is the jQuery code I am u ...

Utilize JavaScript in conjunction with encfs for enhanced encryption capabilities

I am attempting to access an encfs filesystem using JavaScript, but am struggling to understand the correct approach. I am utilizing the CryptoJS library for this task. The .ecnfs6.xml file contains standard settings and uses the password "123456": < ...

Customizing Vue: Implementing an automatic addition of attributes to elements when using v-on:click directive

We are currently working with single file Vue components and we're facing a challenge in our mousemove event handler. We want to be able to determine if the target element is clickable. Within our Vue templates, we utilize v-on directives such as: v- ...

Guide to setting up a horizontal button menu and dropdown submenu beneath the navigation bar using Bootstrap 4

How can I design a horizontal button menu with submenus below the navigation bar in Bootstrap 4? Take a look at the image below to see what I'm aiming for: https://i.sstatic.net/j6b8a.png https://i.sstatic.net/rmtrM.png If you have any ideas or su ...

AngularJS directive is throwing an error regarding an unknown provider

Upon loading my modal in the AngularJS application, an error message is displayed: $injector:unpr Unknown Provider Unknown provider: eProvider <- e The directive implemented is as follows: (function () { angular.module('myApp').d ...

Protecting website pages on both the admin and user side in Next.js 14 to ensure maximum security

I'm currently using nextjs 14 and I am working on developing a website similar to a property app. It will have an admin dashboard and a user side. How can I ensure the security of both the admin and user sides, and what should my folder structure look ...

How to set the "checked" attribute on an md-radio-button using Angular

How can I dynamically check an md-radio button? The website only shows how to do it in scope in app.js, but my attempts with ng-checked have been unsuccessful. Is there a way to modify the JavaScript variable data of $scope to add the checked property? ...

Updating a property of a JavaScript class using a callback function inside the class method after an AJAX request

Here is the code snippet from my JavaScript file: var myApp = myApp || {}; myApp.TestClass = function () { this.testProperty = null; } myApp.TestClass.prototype = { constructor: this, testMethod: function () { var testClass = this; ...

Angular makes it easy to perform HTTP requests using the `http

Greetings! Here is the JSON data for "names" : [ { "file": "file1.zip", "date": "12-03-2016", }, { "file": "file2.zip", "date": "24-06-2016", }, { "file": "file3.zip", "date": "02-12-2016 ...

Proper method for calling a function within a specific scope

I am utilizing user-contributed modules that I aim to avoid editing in order to make upgrades easier. My goal is to enable users to browse for a CSV file on the local filesystem, parse it, and display it in a dynamic table. For this task, I am using PapaP ...

Passing values from Vue3 child component to parent component

Hey there, I'm currently diving into the world of Vue and I'm working on a table that dynamically displays abbreviations. I've been trying to send a searchTerm from my child component to the parent component, but I'm struggling with ge ...

The values in my array are causing it to output NAN

I'm currently working on a program that aims to combine a variable number of one-row matrices with varying lengths. The goal is to add the elements of each matrix together, where element one of array one adds to element one of array two, and so forth. ...

Error Message: Unable to access properties of an undefined object while interacting with an API in a React application

Creating a Weather application in React JS that utilizes the OpenWeatherMapAPI to display dynamic backgrounds based on the API response. I need to access the data at 'data.weather[0].main' which will contain values like 'Clear', ' ...

Receiving JSON dynamically (using socket.io) may result in parsing issues

I am currently working with JSON data that is correctly formatted at 100% accuracy. My issue arises when I execute the following code successfully: var data = {"datas":[{"matts":{"active":"1","status":"off"},"config":null,"adapters":[]}}]}; console.dir( ...