Search code examples
attributesdirectiveangular-formly

I can't add ng-cnpj directive using angular-formly


Anyone know how can I add an directive on my formly object field?

I have the ng-cnpj (https://github.com/gil/ng-cpf-cnpj) directive and want to add it in my cpf field on my controller.

....
    {
      key: 'cnpj',
      type: 'maskedInput',
      templateOptions: {
        type: 'text',
        label: 'CNPJ',
        placeholder: '00.000.000/0000-00',
        mask: '99.999.999/9999-99',
        required: true
      }
....

Solution

  • I resolved it creating a custom type in formlyConfig. The following, my code solution:

    (function () {
    'use strict';
    
    angular.module('app.runs', ['formly', 'formlyBootstrap', 'ngMask'])
    
    .run(function (formlyConfig, $rootScope) {
    
      // mask from ngMask
      formlyConfig.setType({
        name: 'maskedInput',
        extends: 'input',
        defaultOptions: {
          ngModelAttrs: { // this is part of the magic... It's a little complex, but super powerful
            mask: { // the key "ngMask" must match templateOptions.ngMask
              attribute: 'mask' // this the name of the attribute to be applied to the ng-model in the template
            },
            // applies the 'clean' attribute with the value of "true"
            'true': {
              value: 'clean'
            }
          },
          // this is how you hook into formly's messages API
          // however angular-formly doesn't ship with ng-messages.
          // You have to display these messages yourself.
          validation: {
            messages: {
              mask: 'Dado inválido!'
            }
          }
        }
      });
    
    
      // My CNPJ Custom Type
      formlyConfig.setType({
        name: 'rbCnpj',
        extends: 'maskedInput',
        wrapper: ['bootstrapLabel', 'bootstrapHasError'],
        template: '<div class="form-group">' +
                    '<input ng-model="model[options.key]" class="form-control" ng-cnpj />' +
                  '</div>',
        defaultOptions: {
          templateOptions: {
            type: 'text',
            label: 'CNPJ',
            placeholder: '00.000.000/0000-00',
            mask: '99.999.999/9999-99',
            required: true
          }
        }
      });
    
    });
    
    })();