Issue with Angular custom directive failing to set value even after promise resolution

I created a custom directive that works well when the user enters a value. However, I'm facing an issue where the input field is not being rendered when the form is loaded. Below is my directive code:

   var cuitModule = angular.module('cuitModule', []).directive('cuitDirective', ['$filter', function ($filter) {
  return {
      require: '?ngModel',
      link: link,
      restrict: 'E',
      scope: {
          cuitPlaceholder: '=placeholder'
      },
      templateUrl: 'js/common/directives/cuit/cuit.directive.html'
  };

  /*
   Intended use:
   <cuit-directive placeholder='prompt' model='someModel.cuit'></cuit-directive>
   Where:
   someModel.cuit: {String} value which to bind only the numeric characters [0-9] entered
   ie, if user enters 20-33452648-9, value of 20334526489 will be bound to model
   prompt: {String} text to keep in placeholder when no numeric input entered
   */
  function link(scope, element, attributes, ngModel) {

      // scope.inputValue is the value of input element used in template
      scope.inputValue = ngModel.$viewValue;

      scope.$watch('inputValue', function (value, oldValue) {

          value = String(value);
          var number = value.replace(/[^0-9]+/g, '');
          // scope.cuitModel = number;
          scope.inputValue = $filter('cuit')(number);
          var valid = validarCuit(number);
          ngModel.$setValidity('required', valid);
          if (valid) {
              ngModel.$setViewValue(number);
          }
      });

      //source https://es.wikipedia.org/wiki/Clave_%C3%9Anica_de_Identificaci%C3%B3n_Tributaria#C.C3.B3digo_Javascript
      function validarCuit(cuit) {

          if (cuit.length !== 11) {
              return false;
          }

          var acumulado = 0;
          var digitos = cuit.split('');
          var digito = digitos.pop();

          for (var i = 0; i < digitos.length; i++) {
              acumulado += digitos[9 - i] * (2 + (i % 6));
          }

          var verif = 11 - (acumulado % 11);
          if (verif == 11) {
              verif = 0;
          }

          return digito == verif;
      }
  }}]).filter('cuit', function () {
  /*
    Format cuit as: xx-xxxxxxxx-x
    or as close as possible if cuit length is not 10
   */
   return function (number) {
       /*
         @param {Number | String} number - Number that will be formatted as cuit number
         Returns formatted number: ##-########-#
         if number.length < 2: ##
         if number.length < 10: ##-########
         if number.length === 11: ##-########-#
        */
       if (!number) {
           return '';
       }

       number = String(number);

       // Will return formattedNumber.
       // If phonenumber isn't longer than an area code, just show number
       var formattedNumber = number;

       //Type 20, 23, 24 y 27 Personas Físicas or 30, 33 y 34 Empresas
       var type = number.substring(0, 2);

       var main = number.substring(2, 10);
       var verifyNumber = number.substring(10, 11);

       if (main) {
           formattedNumber = (type + '-' + main);
       }
       if (verifyNumber) {
           formattedNumber += ('-' + verifyNumber);
       }
       return formattedNumber;
   };});

This is how it's implemented in HTML:

    <cuit-directive placeholder="'CUIT'" ng-model='vm.merchant.idNumber' required></cuit-directive>

The directive is being used within a form. After fetching data from a REST service, the controller looks like this:

    function EditMerchantCtrl($state, $ionicHistory, merchantsService, $ionicPopup, $timeout, $ionicLoading) {
     var vm = this;
     function init(){
        merchantsService.get().then(
          function(response){
            vm.merchant = response.data;
          });
     }}

However, despite getting the data from the service, the field does not populate as expected. Any assistance on this matter would be greatly appreciated.

Answer №1

To enhance your ngModelController, consider integrating the $render function as shown below:

ngModel.$render = function() {
   scope.inputValue = ngModel.$viewValue;
}

This solution may prove beneficial.

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

Utilizing Parent Method in VueJS Component: A Step-by-Step Guide

I need to access methods of the parent component from within the current one, without using props. Below is the structure in HTML: <div id="el"> <user v-for="user in users" :item="user"></user> </div> And here is the Vue code ...

Is there a way to determine if the browser window is currently in use?

The code I am currently working with looks like this: let focus; function setFocus() { focus = true; } function hideWindow() { focus = false; } window.onfocus = setFocus(); window.onblur = hideWindow(); The intention behind this code is to use it in the ...

Tips for assigning data from an AJAX response to a variable

Using jQuery and the code provided, there seems to be an issue with variable scope when some_condition is false. The error "items is not defined" indicates this problem. The goal is to set the result variable to the AJAX response data in order to use it o ...

leveraging React Router in conjunction with Next JS routing

As a newcomer to Next.JS, I have a simple question about managing routes in my web application. Currently, our project utilizes Next JS to handle routes in the BackEnd. However, I am facing a dilemma where I would like to use React-Router-Dom in a specifi ...

Can anyone recommend any offline editors for HTML, CSS, and JavaScript similar to JSFiddle, jsbin, or codepen?

Is there an alternative to JSFiddle.net that allows users to experiment with Javascript, HTML, and CSS offline in a similar way? ...

What is the best way to incorporate an image zoom-in effect into a flexible-sized block?

Having a fluid grid with 3 blocks in one row, each set to width:33.3%. The images within these blocks are set to width: 100% and height: auto. I am looking to implement a zoom-in effect on hover for these images without changing the height of the blocks. I ...

Step-by-Step Guide on Retrieving Filtered Data using React Context API

Currently, I am in the process of developing a dashboard application using React.js, React Context API, and ApexCharts. The app will visualize a 1000-length JSON data on 7-8 different charts, along with 6-7 variable filters. Overview of the App Structure: ...

Using the `let` keyword in Node.js for variable declaration

Understanding global and local identifiers in Node.js has been a bit tricky for me, especially when working with database query results in the page.evaluate() method. I'm seeking assistance in utilizing variables from a query to subsequently use them ...

Receiving and monitoring events triggered by a Vue component that was dynamically mounted

I am currently mounting a Vue component dynamically within a mixin to incorporate the resulting HTML into a map popup. While everything is functioning correctly, I am facing an issue with listening to events emitted by the component. I am unsure of how to ...

Having trouble with Instafeed JS loading?

I am currently experimenting with instafeed.js, but I am encountering difficulties getting it to load on a basic bootstrap page. While everything else on my page loads successfully, this particular container remains empty without any Instagram code presen ...

Tips for creating a cohesive group of HTML elements within an editable area

Imagine having a contenteditable area with some existing content: <div contenteditable="true"> <p>first paragraph</p> <p> <img width='63' src='https://developer.cdn.mozilla.net/media/img/mdn-logo-s ...

Main navigation category as parent and secondary category as a child menu in WordPress

Hello there, I am looking to create a navigation menu with parent categories displayed horizontally and child categories as corresponding submenus. For example, The parent categories would be Apple, Orange, and Mango Under Apple, we would have apple1, ...

Issue: A React component went into suspension during the rendering process, however, no alternative UI was designated

I'm currently experimenting with the code found at https://github.com/adarshpastakia/ant-extensions/tree/master/modules/searchbar Although I followed the tutorial instructions, I encountered an error. Could it be that the library is malfunctioning? I ...

What is the best way to show an on/off button in an HTML page when it loads, based on a value stored in a MySQL database?

Is there a way to display a toggle button onload based on a value from a MySQL database table? I need the button to switch between 0 and 1 when clicked. I've looked at several solutions but none of them seem to work for me. Any help would be greatly a ...

Expanding Angular route paths with subdirectories

I am in the process of organizing my project in a more structured manner, creating a separate folder exclusively for projects. Within the app.js file, I defined my route as follows: .when('/contact', { templateUrl: 'views/contact.html&ap ...

The navigation bar in React Router is interfering with the loading of other components

Currently, I am in the process of setting up a simple navigation bar that consists of basic buttons without any complex functionality. However, I have encountered an issue where placing the navbar inside the switch prevents other components from loading ...

When provided with varied inputs, new Date() yields distinct values for various time zones

var date1 = "2015-03-29"; console.log(new Date(date1)); //Output:Sun Mar 29 2015 05:30:00 GMT+0530 (India Standard Time) var date2 = "1869-12-31"; console.log(new Date(date2)); //Output:Fri Dec 31 1869 05:53:20 GMT+0553 (India Standard ...

Present pop-up messages in the most sophisticated manner

I have successfully created an AngularJS app that is functioning well. Now, I am faced with the challenge of displaying different pop-ups based on specific conditions being met. I am unsure of the best approach to take. Currently, I am considering two op ...

Generating a new array in NodeJs from data retrieved by querying MySQL

In my NodeJs project, I am trying to generate a new array from the results of a MySQL query. Here is the current result: [ { "availabilityId": 1, "dayName": 1, "fromTime": "05:30:00", "toTime": "10:00:00" }, { ...

How can I access the target element during ng-change event?

I am using an ng-repeat to display multiple textareas, and I need to be able to access the target element when the ng-change event is triggered. <div ng-repeat="item in $ctrl.items"> <textarea ng-change="$ctrl.changed()"></textarea> &l ...