我不能使用angular-formly添加ng-cnpj指令

时间:2016-12-13 18:39:57

标签: attributes directive angular-formly

任何人都知道如何在我的形式对象字段中添加指令?

我有ng-cnpjhttps://github.com/gil/ng-cpf-cnpj)指令,想把它添加到我控制器的cpf字段中。

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

1 个答案:

答案 0 :(得分:0)

我解决了在formlyConfig中创建自定义类型的问题。以下是我的代码解决方案:

(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
      }
    }
  });

});

})();