The storage format of the input field is handled differently on the angularjs controller side

Check out the plunker link for this directive in action. A comma is automatically added as the user types in the input, and it displays numbers with 2 decimal places.

However, there seems to be an issue where entering '2300.34' results in '230034' on the controller side after clicking 'Submit'. This discrepancy can be seen using console.log. The desired outcome is to retain the original data format on the controller end.

The code includes JavaScript and a directive:

var app = angular.module('App',[]);
app.controller('MainCtrl', function ($scope) {

                        $scope.getdata = function(){
                            console.log($scope.amount);
                        }

});



app.directive('format', ['$filter', function ($filter) {
return {
    require: 'ngModel',

    link: function (scope, elem, attrs, ctrl) {
        if (!ctrl) return;


        ctrl.$formatters.unshift(function (a) {
            return $filter(attrs.format)(ctrl.$modelValue);
        });


        ctrl.$parsers.unshift(function (viewValue) {
            var plainNumber = viewValue.replace(/[^\d|\-+]/g, '');
            elem.val($filter('number')(plainNumber/100,2));
            return plainNumber;
        });
    }
};
}]);

In the HTML section:

<body ng-app="App">
<div ng-controller="MainCtrl">
  <input type="text" ng-model="amount" format="number" />
  <input type="submit" ng-click="getdata()" />
</div>

Answer №1

To solve this problem, you can incorporate JavaScript's parseFloat and toFixed functions within your custom $parsers.unshift method:

var modifiedNumber = parseFloat(inputValue.replace(/[^\d|\-+]/g, '')).toFixed(2);

In addition,

return modifiedNumber/100.00

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 sending multiple values to a jquery dialog box

I am seeking assistance with passing multiple values to a jQuery dialog box and displaying them in a table within the dialog box... The HTML content is being rendered in the dialog box through an AJAX call. Here is my AJAX call: $.get(url, function (dat ...

You can obtain the values of multiple div selections using jQuery

In a display with two columns, I want to be able to perform a common operation (such as delete) based on the selection of certain div IDs. If a user selects the div IDs participant_1, participant_4, participant_6 at the same time, I need to collect these ...

Navigating the intricacies of sub-State mapping in Nuxtjs

I have set up a state called ~/store/modules/general/index.js Within this state, there are Actions named get_info and get_pages, as well as states named info and pages. When I use ...mapActions({ getInfo: 'modules/general/get_info' getPages: ...

Encountering difficulties obtaining server response while utilizing dropzone.js version 4

I am currently using dropzone.js version 4 to facilitate file uploads from a webpage to my server. While the upload process is functioning properly, I am encountering difficulty in retrieving the server response. It should be noted that I am creating the D ...

Enhance your property by adding the isDirty feature

Managing changes to properties of classes in TypeScript can be optimized by tracking only the fields that have actually changed. Instead of using an array to keep track of property changes, I am exploring the idea of implementing an isDirty check. By incor ...

Retrieving the real server response using Angular's $resource

I have developed an API using Laravel which provides JSON data in the following format: { "data":{ "errors":{ "username":"The username you entered has already been taken.", "email":"The email address provided is already in use." } ...

Animating toasts in Bootstrap

Exploring the options available at https://getbootstrap.com/docs/4.3/components/toasts/ To customize your toasts, you can pass options via data attributes or JavaScript. Simply append the option name to data- when using data attributes. If you're lo ...

The JSON key has been labeled as "valid", making it difficult to access in JavaScript as demonstrated in a JSfiddle example

Initially, I transformed a Plist file (XML formatted) into JSON using an online tool. Extracting the important data from this extensive JSON file was not a challenge. Utilizing this crucial data, I am reconstructing a new JSON file that is concise and cont ...

Skrollr immediate pop-up notification

Can anyone help me figure out how to make text appear suddenly and then disappear using skrollr? I've been able to get it to fade in and out, but I want it to just show up without any transition. Here's the code I have so far: <div id="style" ...

"Learn the steps to toggle a sub menu using an onclick event and how to hide it using another

I created a sidebar navigation that displays submenus on mouseover, but I want them to open on click and close when clicking on the same tab. Please take a look at my code on this CodePen link. Thank you. <nav class="navigation"> <ul class="mai ...

What is the best way to split a string in Java so that it separates the full name into first name and last name?

Is there a way to rearrange a string that is entered through the keyboard? For instance, let's say I want the user to provide a name in the format "last name, first name" and I need to convert it to the format "first name last name". Below is the cod ...

Limiting the style of an input element

How can I mask the input field within an <input type="text" /> tag to restrict the user to a specific format of [].[], with any number of characters allowed between the brackets? For example: "[Analysis].[Analysis]" or another instance: "[Analysi ...

choose and adjust elements within a three-dimensional scene using three.js

I have a JSON file containing object data that I load into my scene using ObjectLoader. After adding the objects to the scene, I want to customize their textures by adding parameters like THREE.SmoothShading and an envMap. I know how to find a specific obj ...

Disappear solely upon clicking on the menu

Currently, I am working on implementing navigation for menu items. The functionality I want to achieve is that when a user hovers over a menu item, it extends, and when they move the mouse away, it retracts. I have been able to make the menu stay in the ex ...

A guide to resolving the error "Unable to find 'require' in vuejs"

I am currently working on a project using vuejs and firebase. I encountered an issue while trying to import firestore. When I accessed my page, I saw this error message in the console: ReferenceError: require is not defined I attempted to place the import ...

Learn how to toggle multiple class elements with jQuery, and how to hide the ones that have

This is an example of my HTML code: <h4 class="list-group-item-heading"> @Model.Customer.FirstName @Model.Customer.LastName wrote: <span class="right"><span class="icon-file padding-right link"></span></span> </h4& ...

AngularJS in action for a new Widget Framework

I am working on a project that requires creating a page similar to iGoogle. This page will consist of various drag-and-drop widgets, with each widget representing a distinct application. Does anyone have any advice or recommended links for this type of pr ...

The 'sticky' nature of Firebase Authentication in Ionic

I have been working on integrating $firebaseAuth into my Ionic project. I followed a sample example from the Firebase website for logging in with Twitter (auth.$authWithOAuthPopup('twitter')) and incorporated it into my Ionic Framework. The code ...

Displaying Component when Clicked using Vue.js

How can I display a modal component after an "on click" event? Is it possible to show a component using a method call, or what is the recommended approach in this scenario? Here is my specific use case: I have multiple cards each containing various infor ...

When implementing a Vue component, you may encounter a 'parentNode' TypeError

I'm experiencing an issue with a page that is only partially rendering. Specifically, the page renders Listings but not Bookings. After some investigation, I discovered that removing the divs associated with isReviewed() resolves the rendering issue. ...