Mask input in AngularJS

I am currently working on developing a custom directive for creating personalized masks for input fields. While there are other libraries available, I often need to create specific input formats tailored to the company's requirements (e.g., "OS.012-08765"), so I prefer to build my own directive.

So far, I have successfully formatted the number according to the specified pattern, but only in the model and not in the actual input field. For this demonstration, I will be using a money input because it is easier to work with (in my opinion). Here is the code I am utilizing:

function myMoney() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attr, ngModelCtrl) {
            ngModelCtrl.$formatters.push( formatInput );
            ngModelCtrl.$render = renderViewValue;
            ngModelCtrl.$parsers.push( parseOutput );


            function formatInput( value ) {
                value = formatNumber(value);
                return value;
            }
            function parseOutput( value ) {
                value = formatNumber(value);
                return value;
            }
            function renderViewValue() {
                element.html( ngModelCtrl.$viewValue );
            }

            function formatNumber(value) {
                if(!value) {
                    value = '000';
                }

                var checkValue = value.replace(/[^0-9\.]/g, '');
                if(checkValue != value) {
                    value = checkValue;
                }

                value = value.toString();

                if(value.length < 3) {
                    value = ('000'+value).slice(-3);
                }

                var 
                    firstChar = value.slice(0, value.length-2),
                    lastChar  = value.slice(-2),
                    firstChar = Number(firstChar).toLocaleString(),
                    finalChar = '$'+firstChar+','+lastChar;

                return finalChar;
            }
        }
    }
}

Here is the Plunker link with the provided code: http://plnkr.co/edit/UjZkPFL0V4FRrDUL9jAJ?p=preview


The main issue arises when typing in the input field as the value lacks the desired mask and displays only numbers. However, the model retains the correct formatting.

Based on this problem, I am facing two main challenges:

  • Firstly, I aim to switch these outcomes where entering text in the textbox exhibits the mask while the model remains plain numbers without any masking.
  • Secondly, even when creating an update button to modify the model value, it does not adhere to the set mask and displays the plain text instead.

How can these issues be effectively resolved?

Answer №1

Consider utilizing the UI mask feature for enhanced user input control. Visit this link and input AA.999-99999 in the Mask Definition field to customize the pattern as needed.

<input type="text" 
       ng-model="serviceOrderNumber" 
       ui-mask="AA.999-99999"  
       ui-mask-placeholder 
       ui-mask-placeholder-char="_"/>

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

Obtain the distinct highest value for every vertical axis on a bar graph

I'm facing an issue with my code where I am appending multiple SVG elements and generating 3 different charts. The problem is that the maximum value evaluated from the y.domain() for each y-axis is taken as the maximum value from all of my data. Is t ...

What is the most effective method in React JS to achieve real-time results with every keystroke by making REST calls to the server?

We are dealing with a huge database and the task at hand is to display results as the user types them in the search box. Preloading queries to attempt matching is out of question due to the enormity of our data. Currently, we make a server request with th ...

Update the content within a div based on the selected option from a dropdown menu or

Is there a way to change the displayed text based on user input or selected option? By default, the text shown is "Aa Bb Cc Dd Ee...", but it can be changed by selecting different options. If text is typed into the input field, the displayed text will up ...

jQuery scrollTop animates to the start of the webpage

Upon loading the page, the div appears at the top of the screen but then jumps to its correct position once scrolling begins. To view the website, click on this link: calretirement.com/classes-test.php CSS: .register{position:fixed !important; bottom:1 ...

What is the method to retrieve the image's value after dropping it onto the droppable area?

I have implemented a drag and drop feature using jQuery, and I am trying to extract the value of an image and insert it into a database. Additionally, I want to update and remove the image value when it is removed from the droppable area. How can I achie ...

How to Retrieve the Absolute Index of the Parent Column Using jQuery Datatables

I recently developed a custom column filtering plugin for datatables, but I've encountered a minor issue. Within each column footer, I have added text inputs, and now I am trying to capture their indexes on keyup event to use them for filtering. In ...

What is the best way to eliminate HTML <li> bullets using codebehind?

When working in codebehind, I often create an HTML list using the following method: HtmlGenericControl list = new HtmlGenericControl("ul"); for (int i = 0; i < 10; i++) { HtmlGenericControl listItem = new HtmlGenericControl("li"); Label textLabel ...

Enhancing AngularJS routing with dynamic partial parameters

I have experience working with routes in different frameworks like Rails and Laravel, but I am now facing a challenge while working on an AngularJS site. In Laravel, we could dynamically create routes using foreach loops to handle different city routes. Ea ...

React - updating key prop does not trigger re-render of child component

I have implemented react-infinite-scroll to display a continuous feed of data. My goal is to refresh the data feed whenever the user makes any changes to their settings. To achieve this, I am utilizing a key prop for the InfiniteScroll component. The conc ...

Assistance needed with selecting elements using jQuery

After some practice with jQuery, I managed to select this specific portion from a lengthy HTML file. My goal is to extract the values of subject, body, and date_or_offset (these are name attributes). How can I achieve this? Let's assume this snippet i ...

What could be causing the issue of being unable to connect to the NodeJS express server from any network?

Imagine having a web server running on port 3001 with the IP address 23.512.531.56 (obviously not a real one) and then switching to another network, like your neighbor's. Now, when you try entering 23.512.531.56:3001 in Chrome, why doesn't the se ...

What is the best approach to transform a lengthy collection of 'watch' statements into a functioning solution using VueJS?

I am new to vueJS and need some help with optimizing my code. I have a long list of watch functions that are all essentially the same, but I'm not sure how to convert them into a more efficient and functional approach. These watch functions are all r ...

Error: The property 'ss' cannot be accessed because it is undefined

Our main source page will be index.html, while Employees.html is where our results end up. An error occurred: TypeError - Cannot read property 'ss' of undefined Error in the code: let rating = req.body.ss; Seeking assistance please >< C ...

"Implementing Vue mousemove functionality only when the mouse button is pressed

Is it possible to initiate a mouse movement only after the element has been clicked first? I am exploring this functionality for an audio player timeline. .player__time--bar(@mousedown="setNewCurrentPosition($event)") .slider(role="slider" aria-valuem ...

JS Nav Dots are not activating the Active Class

I have been utilizing a code snippet from this source to incorporate a vertical dot navigation feature into a single-page website. The navigation smoothly scrolls to different sections when a link is clicked, with an active highlight on the current section ...

Utilize Hardhat and NPM to distinguish between unit tests and integration tests efficiently

Struggling with setting up two commands in my package.json for running unit tests and integration tests. I am having trouble defining the location of the testset for each type of testing. Within the scripts section of my package.json, I have created two c ...

Enhancing Win8 apps with AppendTo/jquery-win8

Recently, I've been intrigued by the ToDoMVC samples and decided to try porting them into a Windows 8 JS app. I thought it would be as simple as copying and pasting the code while making sure to reference the necessary WinJS libraries. However, I soo ...

iPad2 always displays UIWebView in 'portrait' orientation

I have a sophisticated HTML5 website that includes JavaScript. It is displayed in a UIWebView. The JavaScript on the page is supposed to determine whether the iPad is in Portrait or Landscape mode. Unfortunately, I have encountered an issue. Regardless of ...

The selection elements fail to reset correctly

I'm currently working on an Angular 4 application where I have a form that includes a select element inside a box. <div class="form-group"> <label for="designation">Designation</label> <select [class.red-borde ...

React virtual list module: Scrolling down through code commands

In my React Grid with Virtual Scrolling, I am facing a challenge with the lack of a "scroll to row feature." At times, I need to select a specific row programmatically and ensure that it is displayed to the user. Although I have the ID of the desired row ...