Why isn't $viewValue being implemented in the textbox directive?

How to Implement Masking in AngularJS
I'm trying to apply masking to $viewValue in my console, but it's not reflecting in the view.

NgModelController {$viewValue: "656-56", $modelValue: "656565", $$rawModelValue: "656565", $validators: Object, $asyncValidators: Object…}

Sample Code :

var app = angular.module("masking",[]);
app.directive('textbox', function mask() {
      return {
        restrict: 'E',
        transclude: true,
        require: 'ngModel',
        scope: { },
        bindToController: {
            model: "=ngModel",
        },
        controller: function($scope, $attrs) {

        },
        compile: function() {
            return {
                pre: function(scope, el, attrs) {
                },
                post: function(scope, element, attrs, Ctrls) {
                 }
            };
        },
        template: '<div><input type="text" ng-model="Ctrl.model" /> </div> ',
        controllerAs: 'Ctrl',
    };
});

app.directive('angularMask', function () {
    return {
      restrict: 'A',
      require: 'ngModel',
      scope: false,
      link: function ($scope, el, attrs, model) {
        $scope.$watch(function(){return attrs.angularMask;}, function(value) {
          if (model.$viewValue != null){
            model.$viewValue = mask(String(model.$viewValue).replace(/\D/g, ''));
            el.val(model.$viewValue);
          }
        });

        model.$formatters.push(function (value) {
          return value === null ? '' : mask(String(value).replace(/\D/g, ''));
        });

        model.$parsers.push(function (value) {
          model.$viewValue = mask(value);
          var modelValue = attrs.isModelValueEqualViewValues ? model.$viewValue : String(value).replace(/\D/g, '');
          el.val(model.$viewValue);
          return modelValue;
        });

        function mask(val) {
                    console.log(model);

          var format = attrs.angularMask,
          arrFormat = format.split('|');

          if (arrFormat.length > 1) {
            arrFormat.sort(function (a, b) {
              return a.length - b.length;
            });
          }

          if (val === null || val == '') {
            return '';
          }
          var value = String(val).replace(/\D/g, '');
          if (arrFormat.length > 1) {
            for (var a in arrFormat) {
              if (value.replace(/\D/g, '').length <= arrFormat[a].replace(/\D/g, '').length) {
                format = arrFormat[a];
                break;
              }
            }
          }
          var newValue = '';
          for (var nmI = 0, mI = 0; mI < format.length;) {
            if (!value[nmI]) {
              break;
            }
            if (format[mI].match(/\D/)) {
              newValue += format[mI];
            } else {
              newValue += value[nmI];
              nmI++;
            }
            mI++;
          }
          return newValue;
        }
      }
    };
  });

Example HTML Code

<textbox ng-model="myModelPhone" angular-mask="000-000-000"></textbox>
    {{myModelPhone}}

Check out this JSFiddle link for reference.

Answer â„–1

It is not recommended to apply the angular-mask directive on the same element where the textbox directive is used. This is because it will affect the ngModel of the textbox model instead of the inner ngModelController.

To resolve this issue, you should make a slight change to your directive structure. In the textbox directive, simply pass the masking pattern as an attribute like masking-pattern="000-000-000"

Then update the directive template as follows:

template: function(element, attrs){
   return '<div><input type="text" ng-model="Ctrl.model" angular-mask="'+attrs.maskingPattern+'"/> </div> '
}

Example in HTML:

Text box directive: <textbox ng-model="myModelPhone" masking-pattern="000-000-000"></textbox>
{{myModelPhone}}

Check out the demo on Fiddle

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

The webpage displays the element as <span class="icon">&#xe80d;</span> instead of rendering it properly

In my ReactJS project, I have created a component called Menu1item: class Menu1item extends React.Component{ render(){ return ( <div> {this.props.glyph}{this.props.value} </div> ) ...

The functionality of AngularJS's ng-repeat is to aggregate the values within

Hello, I am a beginner in angularjs and I'm facing an issue with calculating the sum of values in a field. Here is my code snippet: <div ng-repeat="(key,item) in expenses_data | groupBy: 'category_name'"> <h4 ng-cloak><i c ...

It seems that Firefox is ignoring the word-wrap style when the class of a child element is changed

Take a look at this: var iconIndex = 0; var icons = ['check', 'chain-broken', 'flag-o', 'ban', 'bell-o']; $('button:eq(0)').click(function() { iconIndex = (iconIndex + 1) % icons ...

Initializng an array with null values in Javascript

Can you explain why this Javascript code: var myArray = new Array(3); does not produce the same result as: var otherArray = [null, null, null]; ? Keep in mind that (myArray == otherArray) returns false. Additionally, is there a way to create an ...

Error encountered while building with Next.js using TypeScript: SyntaxError - Unexpected token 'export' in data export

For access to the code, click here => https://codesandbox.io/s/sweet-mcclintock-dhczx?file=/pages/index.js The initial issue arises when attempting to use @iconify-icons/cryptocurrency with next.js and typescript (specifically in typescript). SyntaxErr ...

JavaScript Cookie Array Handling

Is it possible to create a 2D array as a cookie in JavaScript? If so, how can I go about creating this array cookie and looping through it to retrieve data efficiently? Any guidance on this would be greatly appreciated. Thank you! ...

Tips for choosing this element (using Python)

As I work on getting a selector for the action-button class using Selenium in Python, I am utilizing a Javascript Document QuerySelector. This involves executing some js code via the WebDriver, as demonstrated below: printBtnlast = driver.execute_scrip ...

Nested Views in Angular UI Router

I have a specific structure set up like this: <div ui-view="main"> <!-- content is dynamically loaded here by AngularJS ui-router --> <aside ui-view="sidebar"> <!-- sidebar content is also populated by AngularJS ui-router --&g ...

generating a new item using Mongoose searches

How can I generate an object based on queries' results? The table in the meals operates using database queries. How do I handle this if the queries are asynchronous? const getQueryResult = () => { Dinner1300.count().exec(function (err, count) ...

Issue encountered when toggling flip switch in Jquery Mobile

I am trying to create a calculator for my app using Jquery Mobile, but I am facing an issue with the flip toggle switch. Here is my script: <script type="text/javascript"> function dosis() { $peso = $('#peso').get(0).value $dosis = ...

The most efficient and hygienic method for retrieving a value based on an observable

Looking at the structure of my code, I see that there are numerous Observables and ReplaySubjects. When trying to extract a value from one of these observables in the HTML template, what would be the most effective approach? In certain situations, parame ...

Modifying the class when ng-focus is triggered in AngularJS

Here is the HTML code that I am working with: <div class="icon fluid select" ng-init="focused = false"> <i ng-class="{'large svg guests icon':rooms==2, 'large svg guest icon':rooms==1,'active':focused==true}"> ...

I'm having trouble getting my state to update in React when using useState

I am facing an issue with rendering a component that has a route using react router. The first component contains a button, and upon clicking it should render another component with state passed down from the initial component. However, even though the pag ...

Creating a horizontal scroll effect using jQuery when the widths of the items are not

I am working on a jQuery gallery that showcases images in a horizontal layout. Below the images, there are "left" and "right" buttons which allow users to scroll through the pictures. There are many tutorials and plugins available for this type of function ...

Obtaining a collection of network interfaces using node.js (ioctl SIOCGIFCONF)

As a newcomer to node, I am exploring the possibilities of using node_pcap to capture packet data and perform interesting actions with it. One important aspect of this process is determining the network interface to monitor, such as "eth0". I had an idea ...

"Utilizing Vue.js to determine whether a checkbox is filled with data or left

My goal is to create a checkbox using vue js without writing a method. I want the checkbox to default to false, and when checked, I want the data "opening_balance" to be an empty array. Conversely, if the checkbox is unchecked, I want it to be omitted when ...

What is the best approach to calculate the number of days between two dates using React JS within a map function?

Looking for a way to calculate the difference between two dates using the ReactJs jsx map loop. Data to work with: { departureDate: '2020-07-28', returnDate: '2020-09-16', } React Component: const DaysDiff = () => { ...

Angular not displaying input value correctly in first loop index

Hello, I am currently working on a rent calculator application using Angular. The app takes three inputs: total rent, annual rent increase amount, and the number of years to calculate for. One issue I am facing is that the for loop does not print the enter ...

Most efficient method for comparing two JSON arrays and rearranging their positions

I am faced with a challenge involving two Javascript JSON arrays. The arrays in question are named this.BicyclePartsOLD and this.BicyclePartsNEW. Both arrays contain an attribute named "ListOrder". The OLD array is currently ordered from ListOrder 1 to n ...

Using Session Value to Automatically Select Drop Down Box

<select> <?php foreach($result as $city) { ?> <option value="<?php echo $city->city_name; ?>" <?php if( strtolower($this->session->city) == strtolower($city->city_name) ) { echo "selected"; } ?> ...