The directive I created is being disrupted by the Angular require directive

Recently, I created a custom directive inspired by a solution on Stack Overflow that restricts user input to only digits:

     .directive('onlydigitinput', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, modelCtrl) {
            modelCtrl.$parsers.push(function (inputValue) {
                var transformedInput = inputValue.toLowerCase().replace(/ /g, '')
                  .replace(/[^0-9]+/g, '');
                if (transformedInput != inputValue) {
                    modelCtrl.$setViewValue(transformedInput);
                    modelCtrl.$render();
                }
                return transformedInput;
            });
        }
    };
})

Initially, the directive worked perfectly. However, when I combined it with the 'required' directive, issues started to arise.

The HTML snippet I used was:

input(type='text' , required, onlydigitinput,  min='1', max='99', maxlength='2')

I avoided using type='number' due to a bug in Chrome that disregarded the maxlength attribute and interfered with my directive. Everything works fine when entering digits, but the problem occurs when starting with a non-digit character. In this case, I receive the following error message:

TypeError: Cannot read property 'toLowerCase' of undefined
at http://localhost:3000/scripts/core/directives/systemDirectives.js:63:54

This error seems to be caused by the toLowerCase function in my directive. I am seeking advice on how to resolve this error and enhance the performance of my directive to handle such scenarios effectively.

Answer №1

Ensure that your input field has a required field validator, so that when you leave the field blank - which can occur when you enter a non-digit character - the value will be set to undefined.

var transformedInput = inputValue.toLowerCase().replace(/ /g, '').replace(/[^0-9]+/g, '');
            if (transformedInput != inputValue) {
                modelCtrl.$setViewValue(transformedInput);
                modelCtrl.$render();
            }

Incorporate the following code snippet at the beginning of the existing code:

if(!inputValue) return ;

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

Emphasize a thumbnail by decorating it when selected in the gallery display page

I have created a gallery.php file with the following code: <div id="galleryImage"> <ul> <li> <a href= "gallery.php?imgName='artistvan'"> <img src="thumbnail/artistvan.jpg" ti ...

Experiencing difficulties in installing opensea-js using NPM

While working on my project, I encountered an issue when trying to install opensea-js as a dependency. My Node version is v14.16.0 and NPM version is v7.7.5. Every time I run the command npm install --save opensea-js, it results in an error. I attempted c ...

Restangular adding newly created models to collection following a POST request

When adding a model to a restangular collection using post method, I encountered an issue. var collectionService = restAngular.all('collection'); var collection = collectionService.getList(); var item = { title : "A title" }; collection.pos ...

What strategies can I implement to prevent the JavaScript CallStack from becoming overloaded?

The code snippet below outlines the functionality achieved through JavaScript (specifically for a node.js COMET application): A request is sent to the server and held until there is a response. Upon receiving a response, the data is processed, and anothe ...

The interval keeps resetting every time I want the initial one to expire first

I'm currently working on a battle system that utilizes intervals, and I've encountered an issue where it keeps refreshing instead of creating multiple intervals. When I stop pressing the button associated with it, everything goes back to normal. ...

Utilizing an Angular expression within a bespoke directive

Here is the directive that I am currently working with: gymApp.directive('ngListar', function() { return { templateUrl: function(elem, attr){ console.log(attr.type); return 'js/directives/listar-&apos ...

Programmatically adding route resolve in Angular using $routeProvider

Is it possible to dynamically add Angular's resolve after it has been initially defined in the app? Let's say we have a setup with routes like this: app.config(['$routeProvider', function ($routeProvider) { $routeProvider ...

ng-repeat not functioning properly with FileReader

Here is a look at how my view appears: <body ng-controller="AdminCtrl"> <img ng-repeat="pic in pics" ng-src="{{pic}}" /> <form ng-submit="postPic()"> <input id="photos" type="file" accept="image/*" multiple/> <button> ...

Activate background functionality while modal is active in Bootstrap 4

I have come across similar questions addressing the need to change the following: .modal-backdrop { display: none; } However, my modal does not have this .modal-backdrop. I am unsure if this is a new feature in Bootstrap 4, but the mentioned solution ...

Navigation issue discovered while trying to implement Ionic's collection-repeat feature

As a newcomer to Ionic and Angular.js, I recently downloaded an example of an ionic collection repeat and navigation from http://codepen.io/ionic/pen/mypxez. Initially, the example worked perfectly with just single index.html and index.js files. However, I ...

Exploring UI-Grid: Retrieving binding values within deeply nested JSON arrays

Is there a specific syntax for accessing binding values in nested JSON arrays? I'm struggling with filtering addresses in an array within AngularJS. Here is a plunker demonstrating the issue: http://plnkr.co/edit/tizLxnAtgqDnptiEb3mg?p=preview In my ...

Tips for executing an asynchronous fetch prior to the first rendering

Currently, I am working with the Wordpress API using Next.js on the front end. My goal is to fetch my navigation/menu data and have it pre-rendered. However, my attempts have only resulted in an empty <nav> </nav> element being rendered when I ...

Exploring JSON Array Data and Its Sub-Properties in React

I have a JSON array containing personal data that I want to access from my React app. This JSON file is already included in my React application. { "person": [ { "id": "userId", "sellerImage": "https://i.pravatar.cc/300", ...

Jumbling a word by shuffling its letters into a random order

The objective of the program is to take the word you input into a box, split it into an array of letters, and then shuffle them. Following that, it should capitalize the first letter and lowercase the rest before displaying the result in the same box. I a ...

Ensuring Type Safety in Typescript

I have a specific requirement where I need to validate the structure of a request body to ensure it conforms to a predefined type. Is there a way or a package that can help achieve this validation? type SampleRequestBody = { id: string; name: string; ...

The issue I am facing is with the post_logout_redirect_uri not functioning properly when using localStorage in an OIDC Auth

authority: 'yyy', client_id: this.'yyy', redirect_uri: 'http://localhost:4200/login', response_type: 'token', scope: 'yyy', post_logout_redirect_uri: & ...

How can I integrate Apple remote support into a website with the use of Javascript?

One thing that I find interesting is the ability to use the Apple remote with Front Row, as well as other apps on Mac that support it. I'm curious about whether Web Apps could also be made compatible through Javascript. I have a concept for a TV-like ...

The $scope.$watch function is not triggering events within a controller of a ui.bootstrap.modal

Currently, I am utilizing UI bootstrap for Angular and have successfully integrated the ui.bootstrap.modal component into my project. Everything seems to be working smoothly except for one issue I am encountering. Despite setting up a $scope.$watch to trac ...

Exploring the translateZ values in Three.js [tutorial]

I've been searching high and low for the answer to my problem, but I can't seem to find a solution anywhere. I'm attempting to determine the position values that would result from an object translating Z by -100, without actually performing ...

Mobile-friendly persistent navigation located beneath the header, inspired by the iOS7 browser design

This issue is really causing me a headache and slowing down progress on my project because I can't seem to figure it out. Currently, I am working on designing a mobile-friendly website and conducting tests in iOS7/OSX. The layout I am aiming for inc ...