The $formatters directive plays a role in modifying the ngModel as it is

I am facing an issue with using $formatters.

My objective is to conceal the phone number, while displaying only the last 4 characters. It should not display anything if left blank. If text is entered, the model is impacted by the mask and the hidden phone number is saved in the database...

Below is the directive I am utilizing:

.directive('tsHideField', function () {
return {
    require: 'ngModel',
    restrict: 'A',
    link: function (scope, element, attributes, controller) {

        var maskValue = function (value) {
            if (!value) {
                return "";
            }
            if (value.length <= 4) {
                return value;
            }
            var valueHide = "";
            if (value.indexOf('@') === -1) {
                //leave last 4 chars
                valueHide = value.toString().substring(0, value.length - 4).replace(/[\S]/g, "\u2022");
                return valueHide + value.toString().substring(value.length - 4);
            } else {
                //Email address, keep after @ and hide everything except the last 4 letters before
                valueHide = value.toString().substring(0, value.indexOf('@') - 4).replace(/[\S]/g, "\u2022");
                return valueHide + value.toString().substring(value.indexOf('@') - 4);
            }

        }

        controller.$formatters.push(function (value) {
            return maskValue(value);
        });

    }
};
});

To aid you further, here's a fiddle with a small implementation: http://jsfiddle.net/nqp4qtLk/2/

How can I prevent the model from being affected by the mask?

EDIT: I modified Gr3g's answer to align with my requirements

Check out the updated fiddle here: Updated fiddle

Answer №1

Take a look at my UPDATED code snippets:

If you prefer not to remove *'s :
Fiddle

If it's okay to delete *'s :
Punker

Please note :
If deleting *'s is permitted, in the plunker example I demonstrate that certain actions are restricted:
- Removing star(s) when number(s) are visible.
- Inserting a number between two stars or at the beginning.

The code has expanded, hence only a snippet can be displayed here.
It is essential to implement the $parsers pipeline:

controller.$parsers.push(function(val){
 //Adjust your value
 return modifiedValue || val;
});

I included 2 functions in each pipeline so that a String can be accessed in the necessary function for modifying the value. This approach reduces the need for extensive conversions.

controller.$parsers.unshift(function(val){
  return String(val);
});

You may find ways to optimize it further, but exercise caution during any refactoring to address all scenarios effectively, particularly when dealing with deletion of *'s.

Answer №2

It seems impossible to achieve the desired outcome by simply deleting a point while moving between two points.

To accomplish this task, it is recommended to utilize two separate components: one for typing each character and another to display only the last 4 digits of the phone number.

If you are up for the challenge, you could attempt handling all key events on the input yourself to potentially resolve the issue mentioned at the beginning of my response.

Answer №3

In order to manipulate the value that is saved in the model, you can utilize $parsers.push method.

    var modifyValue = function(value) {
        var originalValue = scope.vm.phone.toString();                   
        var lastFourDigits = value.substring(value.length-4);
        var newString = originalValue.substring(0, originalValue.length-4);
        return (newString+lastFourDigits);   
        // Feel free to implement any logic to change the original value
    }

    controller.$parsers.push(function (value) { 
        return modifyValue(value);
        // Alternatively, customize the functionality as needed.
    });

Check out the updated fiddle here - http://jsfiddle.net/anh9y8d9/3/

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

Start running additional JavaScript code only after the previous one has been fully executed

Scenario: I am facing a situation where I have a web form that is submitted through the following event listener: $('#myForm').on('valid', function (e) { ... } Within this function, I have a code snippet that fetches the geo location ...

Combining JS Tree and Datatables for Enhanced Functionality

I am facing a challenge on my webpage where I have two columns. The left column consists of a checkbox jstree, while the right column contains a table using datatables. Both the table rows and tree are loaded at the start. My goal is to display a row when ...

The most efficient method for documenting $.trigger in JavaScript/jQuery is through the use of JSD

When it comes to documenting in jsDuck, what is the optimal method for capturing the following event trigger: $(document).trigger('myCustomEvent'); ...

Developing with Angular 1.4.8 and JavaScript involves the process of building a constructor function to inherit properties into a third object

DEVELOPER TOOLS Using Angular 1.4.8 and lodash QUERY: REVISIT To clarify my query: Create an object (articles) Apply a constructor Import the properties of a third object, but place it in proto folder to prevent cluttering the root with a large colle ...

Once the data is retrieved and the old image is deleted, attempting to upload the new image still results in the old image being displayed in the Next.js application with React Query

async function fetchTour() { const response = await api.get(`/tour/${router.query.slug}`); return response.data; } const { data: tourData, isLoading, isFetching, isTourError: isError, } = useQuery(['fetchTour', router.que ...

Unable to process get requests on the Ionic application

I've been facing challenges with sending a basic get request to the Google Places API. Click here for the API link However, I keep encountering this error message: XMLHttpRequest cannot load The specified URL…ius=500&types=food&name=cruise ...

The Google Books API has encountered an authentication error with status code 401

Trying to access public data using the Google Books API locally: An error occurred with the authentication credentials. It seems that an OAuth 2 access token, login cookie, or another valid authentication credential is missing. For more information, visit ...

What is the best way to prevent npm install from running in nested workspace directories?

I've recently started utilizing npm workspaces in my project. Here is the structure of the app: . +-- package.json -- packages +-- a | -- package.json -- b -- package.json The npm install script should ideally be executed from ...

I'm looking to filter this array based on the value of a subarray that the user will specify the key and value for. How can I accomplish

Given the input var key="value_0" and var input="hello", I need to filter the array in TypeScript based on these values. The filtering criteria involve checking if the array elements contain a subarray with key="value_0" and if the value of this key includ ...

Chrome is inaccurately reporting the outerHeight value, while IE and FireFox are displaying it correctly

The jquery.smartWizard plugin includes a function called fixHeight that adjusts the height of a wizard step. It is utilized when displaying a step for the first time or revealing hidden divs within the step. The function works correctly in IE and FireFox, ...

An issue with the image filter function in JavaScript

I am currently working on a simple application that applies image filters to images. Below is the code I have written for this purpose. class ImageUtil { static getCanvas(width, height) { var canvas = document.querySelector("canvas"); canvas.widt ...

Setting up the Kik Bot configuration can be a bit confusing at first

After installing @kikinteractive/kik and testing the script in /home/usersite/node_modules/, I find myself at a roadblock. How do I properly import @kikinteractive/kik? 2. Create a bot using the username and API key obtained from . 3. Follow the instruct ...

Why does Froala Editor not maintain formatting when retrieving data from the database?

I've been using the Froala editor to add content on my website, and it's doing well for inserting data into the database. However, I'm facing an issue when retrieving data from the database as it doesn't maintain the original formatting ...

Vue has detected an error during rendering: "TypeError: state.actionInfo.find is not a function"

Using vue.js's cli, I created a basic data register application. The application utilizes lookback.js api with vue cli. The application consists of three pages: show, add, and edit. While the show and add pages function correctly, issues arise when ...

Show complete items in Vue.js

Issue at hand: I am in need of displaying and potentially changing JSON data. My goal is to present it in a directory tree format. The structure of the object is unknown, it could be something like this: "buttons": { "login": "LOGIN", "register": ...

Loading content synchronously

Could you assist me in finding a solution to synchronize the loading of pages and elements? Currently, my code looks like this: $(Element).load(File); ... other commands... window.onload = function () { Update_Elements(Class, Content); } Everything ...

Retrieve the maximum numerical value from an object

My goal is to obtain the highest value from the scores object. I have a global object called "implementations": [ { "id": 5, "project": 'name project', "scores": [ { "id": 7, "user_id": 30, "implement ...

Create a new CSS rule within a class, and remember to save the changes to

Upon opening page 1.html, I utilize JavaScript to dynamically add a background image to the body of the page. To achieve this, I use the following code: document.body.style.backgroundImage = "url(http://www.example.com/image.jpg)"; This code effectively ...

What is the exclusion filter in AngularJS?

I am currently working on implementing a search box with angular in my project: <input type="text" typeahead="item.name for item in list | filter: $viewValue:comparator | orderBy: '+name'"/> As part of this functionality, I am looking to ...

Using AngularJS to showcase nested JSON arrays

Just starting out with angularjs and seeking some guidance. Our angular front-end is connected to a REST API delivering JSON data like this: [ { "category_id":"1", "category_name":"dog", "subcategories":[ { ...