AngularJS directive failing to execute consistently

I wrote a custom AngularJS directive for validating percentage values.

Custom AngularJS Directive

app.directive('validatePercent', function () {
    return {
        restrict: 'A',
        link: function ($scope, elem, attr) {
            $scope.$watch(function () { return elem.val(); },
                function (newVal, oldVal) {
                    console.log("old : ", oldVal);
                    console.log("new : ", newVal);
                    if (newVal < 0 || newVal > 100)
                    {
                        elem.val(oldVal);
                    }
                }
            );
        }
    };
});

Here's the HTML code snippet:

<input validate-percent ng-model="obj.progress" type="number" class="form-control" />

Note that obj.progress is an integer and the input type is set to number.

The issue arises when trying to rapidly change the input field value multiple times consecutively. Sometimes, the value goes below -1 or above 101, even though the condition in the directive is newVal < 0 || newVal > 100.

Looking for assistance in resolving this issue.

UPDATE as of Issue #1:

This problem occurs specifically when users use the mouse wheel to change values. It does not occur when incrementing or decrementing using the keyboard arrow keys.

Answer №1

Instead of relying on $watch, you can manage the validation using focus and blur events.

app.directive('validatePercent', function () {
    return {
        restrict: 'A',
        link: function ($scope, elem, attr) {
            var oldVal = elem.val();
            elem.bind('focus', function(e) {
                oldVal = elem.val();
            });
            elem.bind('blur', function(e) {
                if (elem.val() < 0 || elem.val() > 100)
                {
                    elem.val(oldVal);
                }
            });
        }
    };
});

I trust this solution proves useful.

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

Transform the JSON data to generate a fresh JSON output

I'm seeking help to develop a script that generates JSON data based on specific conditions. As of now, I believe my logic is correct. Any assistance would be greatly appreciated. CURRENT ISSUES: [resolved]I am unable to determine why the duration ...

"Empower your forms with Symfony, jQuery, and Prototype for

I am currently working on creating a dynamic form in Symfony 2.0.13 that allows for the addition and removal of fields, although I am only able to add fields at the moment. I have been following the instructions provided in the documentation at this link, ...

Utilize inline scripts within the views of Yii2 for enhanced functionality

I stumbled upon a jQuery code online that allows for the integration of Google Maps, and I'm looking to implement it in my application to ensure accurate address retrieval. You can find the jQuery code here. Currently, I am working with yii2 Advanced ...

Implementing dynamic URLs using static routing in Express

I'm looking for a way to render a page statically in Express that involves using a dynamic URL. For example, In my forum, users create posts and each post has its unique URL that shows the post when clicked: localhost:8080/posts/postNumber Current ...

Issue with storage functionality in Vuex Axios response

Every time I send data to the Vuex storage using an axios response, for example: ** Sidebar.vue ** created(){ this.getRoles(); }, methods: { getRoles(){ var _this = this var roles = null this.$http.get('/api/userroles/ ...

Tips for creating a shift function without using the splice method

I'm currently working on creating custom functions for common array operations. I've hit a roadblock trying to reimplement the shift method without using splice. Any tips or guidance on how to approach this challenge would be highly valued. Cust ...

Capture all form inputs in a JavaScript array

I am struggling to collect all the form values into a regular array[]. Initially, I was able to achieve this for input tags but after adding some select tags, I am facing difficulties. Previously, for only input tags, this code worked: var content = docu ...

Navigating back to an Angular page from a non-Angular page using Protractor

Is there a specific method to return to an angular page? Below is the input and button code from an HTML (non-angular) page: <input class="value" type="password" 3dsinput="password" name="password"> <input type="submit" value="Submit" name="submi ...

What steps can I take to address the problem of my undefined .length value?

I encountered a length error while executing line 2 in this code snippet. index.js:10 Uncaught TypeError: Cannot read property 'length' of undefined" Sample Code: <div class="formCustomerName"> <label>Name:</label> ...

initiating AngularJS ng-model pipeline on blur event

My $parser function restricts the number of characters a user can enter: var maxLength = attrs['limit'] ? parseInt(attrs['limit']) : 11; function fromUser(inputText) { if (inputText) { if (inputText.length > max ...

Next.js project encountered a TypeError with message [ERR_INVALID_ARG_TYPE]: The "to" argument is expected to be a string type

While working on a Next.js application, I came across a TypeError that is linked to the undefined "to" argument. This issue pops up when I launch my development server using npm run dev. Despite checking my environment setup and project dependencies, I hav ...

Managing repeated calls to a specific get function in nodejs

Utilizing an Ajax call, I am invoking the following GET function every 10 seconds to monitor the status of various URLs. app.get('/getUrl', function(req, res) { var response = {}; var keyArr = []; var urlData ...

Preventing the Sending of Origin Header in Angular 2

I am facing an issue in my Angular2 project where the HTTP service is automatically adding the 'Origin' header with a value to all of the requests. Is there a way to stop Angular2 from including this 'Origin' header in the HTTP calls? A ...

The switch statement remains unchanged for varying variables

Here is some code that I am working with: updateTable(selectedIndex) { console.log("running updateTable function"); let level = ''; // if (selectedIndex == 1){ // this.setState({level: 'day'}) // th ...

Manipulating array elements in MongoDB using sort values in Mongoose JS

I am currently developing a quiz application where teams compete in rounds of 12 questions. After each round, I want to award points to the participating teams based on their performance. The team with the most correct answers will receive 3 points, the se ...

Struggling to make AngularJS routes function properly

After starting from scratch, I rebuilt it with freshly downloaded angularJS (version 1.5.8). I simply placed both angular.js and angular-route.js in the library folder following this setup: https://gyazo.com/311679bf07249109671d621bc89d2d52 Here is how in ...

Display the original content of a previous div element after modifying it using JavaScript

I wanted to simplify the code. In my jsp file, when the document is loaded, the select values are filled in automatically. For instance: <div class="col-sm"> <label style="font-size: 20px;"><fmt:message key="cap.workplace"/>: </ ...

The API results are able to be displayed in the console, but unfortunately cannot be shown on the user interface. Any efforts to map the results will result in an Un

Can anyone help me troubleshoot an issue with displaying information from a free API on my page? I'm developing a cryptocurrency app using React, and while I can see the array data with console.log(response.data), I encounter an error when I try to se ...

Angular 8 project experiencing issues with Bootstrap dropdown functionality

I have successfully installed the packages listed below: npm install --save bootstrap@3 npm install --save popper.js angular-popper npm install jquery --save Afterwards, I included the styles and scripts in the angular.json file in the exact order as sho ...

What could be the reason for receiving the error message "Unresolved variable or type approvedPriceDealerCostForm" in my HTML

I'm working with Angular 8 and facing an issue with sending the approvedPriceDealerCostForm when clicking my button. I keep getting an error that says "Unresolved variable or type approvedPriceDealerCostForm". Please refer to the attached image for mo ...