ways to update ng-model once it has been validated

When using ng-model for input, I want to maintain the original value if an invalid number is entered. How can I accomplish this? For reference, visit the Plunker at: http://plnkr.co/edit/wX7n0jBn1Ek1py4DJHqT?p=preview

The input box utilizes ng-model for binding the value and is defined with a type of number.

<input type="number" name="input" ng-model="example.value" min="0" max="99" required>

Currently, when changing the input, the ng-model also changes simultaneously. Is it possible to delay this change until a valid number is entered? Can ng-change be used for this purpose, or does the ng-model update immediately upon input change, making it difficult for ng-change to retain the original value?

Let's consider an example for clarification:

If the current ng-model value is 10, and I input 50, it will update to 50. Subsequently inputting 5000 will change the value to 5000.

Conversely, if the current value is 10 and I input 'aaa', it should revert back to 10.

Specifically, how can I create a copy of the ng-model to restore the original value when using onchange in the input box?

Answer №1

By utilizing the input type number, you are effectively validating your model. However, it is important to ensure that your form as a whole is valid. For more information on validation with Angular, refer to the documentation here.

If you want the value to change only after the input loses focus, you can use ng-model-options. Your input should be structured similar to this:

<input type="number" name="input" ng-model="example.value" min="0" max="99" required ng-model-options="{ updateOn: 'blur' }">

Answer №2

If you want to ensure that the directive stores the last valid value, you can include a parser function like this:

ngModelCtrl.$parsers.push(function(value) {
  if (value) {
     lastValidValue = value;
     console.log(lastValidValue);
  }
  return value;
});

When needed, you can revert the value back to the last valid one. For an example, you can refer to this plunk: http://plnkr.co/edit/KJL49fPahxGHDfYBvIuW?p=preview

Answer №3

I'm not sure what your end goal is with this, but it might be a good idea to deactivate the save button until the form is confirmed as valid.

Reverting back to the previous value could potentially lead to more issues. Let's say the current value is 10, I change it to 50, indicating that it's valid and the value has been modified. Then I proceed to enter 5000, which value should be reverted back to: 10, 5, or 50?

$scope.$watch('example.value', function(newValue, oldValue) {
     if(newValue != oldValue){
       //validate
       if(!valid)
           $scope.example.value = oldValue;
     }
   });

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

How can I use jQuery UI to slide a div, while also smoothly moving the adjacent div to take its place?

Wishing you an amazing New Year! I am looking to create a smooth sliding effect for a div when a button is clicked. I want the adjacent div to slide alongside it seamlessly, without any clunky motions or delays. Currently, the adjacent div only moves afte ...

Retrieving a function's output in React

Upon attempting to retrieve and log the res.data from my function, I encountered an issue where it returned as undefined. However, when I logged it from within the function, the result appeared normal. const getDefaultState = () => { axios .get ...

Confirm that the array contains exactly 2 elements

Is there a way to confirm that an array contains exactly two specific values, for example: ['foo', 'bar'] After trying different approaches, the closest solution I found looks like this: Yup.array() .of(Yup.mixed().oneOf(['foo&a ...

performing a jQuery AJAX call from a UIWebView during the initial launch of the app following installation

We have a uiWebview that uses jquery for an ajax request to log in. It functions flawlessly on mobile safari and all browsers. However, when the application is launched for the first time after installation, the ajax request seems to be sent out but no re ...

Develop a form containing a date input in a special character-free format, along with a validation feature

I am looking to design a form that necessitates users to input a date in the following format: "ddmmyyyy". No slashes, dots, or any other special characters should be included. Only entries matching this specific format will be accepted as valid, any other ...

Utilizing Angular's `ng-repeat` directive to iterate over an object, implementing conditional statements with `if

Trying to create a sorted collection of cities alphabetically. I have a list of objects that look like this: [{city: 'Liverpool', count: 1000, country: 'United Kingdom'}, ...] Here is how I want the items: L Liverpool (1000) London (2 ...

Using JavaScript to dynamically invoke a function and pass parameters dynamically

Exploring a dynamic method call with parameters in JavaScript. let obj = { method: 'foo1', params: ['one', 'two'] } foo1(p1, p2) { // do something } To execute it => [obj.method](obj.params) Is there a way to dyn ...

Is it possible to invoke a JavaScript function from an Angular controller?

I am working on an Angular controller that displays a Google Map using NgMap. I can add markers to the map by clicking on it, which opens an infoWindow with a link to a JavaScript function. The issue I am facing is that I need to reference Angular methods ...

What is the process of incorporating events into a calendar using jQuery or JavaScript?

$(document).ready(function () { //initialize calendar $(".responsive-calendar").responsiveCalendar({ time: '2016-02', events: { "2016-03-30": {"number": 5, "url": "http://w3widgets.com/responsive-slider"}, "201 ...

Updating NavBar text dynamically based on user login status in React.JS

Within my project, there is a Navigation bar that I access from App.js. Depending on whether I am logged in or not, I want to display different versions of the NavBar. When logged in, the NavBar should have a logout button. And when logged out, it should s ...

Exploring nested JSON information through jQuery's AJAX call

I am encountering an issue with accessing JSON data using a jQuery AJAX request in JavaScript. I keep receiving a 'Cannot read property [0] of undefined' error in the console of Google Chrome. Despite trying different approaches, such as referrin ...

How can you integrate AngularJS-UI with JQuery for seamless functionality?

Currently, I am working through the AngularJS-UI tutorial and have hit a roadblock right at the beginning. I am attempting to implement a basic tooltip feature, all necessary JS files have been included but an error is being thrown by the angularJS-ui mod ...

Angularjs scope throws TypeError when attempting to add an array

As someone diving into the world of Angular and JavaScript, I am tackling the challenge of creating a directive that requires adding an array to the directive's scope. Here's a snippet of the code for my directive: .directive("startupSections", ...

What is the best way to eliminate all whitespace in AngularJS binding strings?

I attempted the following: <div id="{{mystring.replace(/[\s]/g, \'\')}}"></div> However, it does not appear to be functioning as expected. The "mystring" object is located on the $scope and contains a string such as " ...

Displaying a message text upon successful AJAX request

I have a web page with an AJAX request that updates data in the database. After the update, I want to display a message to the user on the webpage confirming that the data has been successfully updated. However, currently, no message is being displayed and ...

Is there a way to initiate multiple AJAX requests once a single request has been completed successfully?

I have created two functions and I want to call the get_name_from_id function when my first ajax function is successful. However, it is not working as expected. When I add an alert in the get_name_from_id function after the jsonString variable like alert ...

"Utilize a custom filter in AngularJS to narrow down data based on specified numerical

Can anyone assist me in creating a filter for AngularJS data? I have two inputs, minAgeInput and maxAgeInput. I want to retrieve all products/objects (using ng-repeat) where the product's minimum age and maximum age fall within the limits set by the ...

Utilizing the URLSearchParams object for fetching data in React

I've implemented a custom hook named useFetch: const useFetch = (url: string, method = 'get', queryParams: any) => { useEffect(() => { let queryString = url; if (queryParams) { queryString += '?' + queryParam ...

Tips for resolving a flickering issue that occurs when switching to an input field with our default value / placeholder plugin

In the realm of web development, numerous plugins cater to the implementation of HTML5's placeholder attribute in older browsers. The plugin we have opted for can be found here. Unlike some other alternatives, this particular plugin, with a few modif ...

What issue is there with the href attribute in the pug file?

/users/mihir/users/[object%20Object]/file.txt My pug file and JS code are set up to render a pug page with links for directories and files in the specified path. The problem arises when adding "users/" plus a username before the directory or filename whil ...