角度格式化格式化程序不起作用

时间:2016-06-14 12:23:51

标签: javascript angularjs angular-formly

带有datapicker字段的格式化程序中的第一个值无效

使用文本输入的类似格式化工具正常

您可以在下面的代码中看到一个示例:



/* global angular */
(function() {

  'use strict';

  var app = angular.module('formlyExample', ['formly', 'formlyBootstrap', 'ui.bootstrap']);

  app.run(function(formlyConfig) {
    var attributes = [
      'date-disabled',
      'custom-class',
      'show-weeks',
      'starting-day',
      'init-date',
      'min-mode',
      'max-mode',
      'format-day',
      'format-month',
      'format-year',
      'format-day-header',
      'format-day-title',
      'format-month-title',
      'year-range',
      'shortcut-propagation',
      'datepicker-popup',
      'show-button-bar',
      'current-text',
      'clear-text',
      'close-text',
      'close-on-date-selection',
      'datepicker-append-to-body'
    ];

    var bindings = [
      'datepicker-mode',
      'min-date',
      'max-date'
    ];

    var ngModelAttrs = {};

    angular.forEach(attributes, function(attr) {
      ngModelAttrs[camelize(attr)] = {
        attribute: attr
      };
    });

    angular.forEach(bindings, function(binding) {
      ngModelAttrs[camelize(binding)] = {
        bound: binding
      };
    });

    formlyConfig.setType({
      name: 'datepicker',
      templateUrl: 'datepicker.html',
      wrapper: ['bootstrapLabel', 'bootstrapHasError'],
      defaultOptions: {
        ngModelAttrs: ngModelAttrs,
        templateOptions: {
          datepickerOptions: {
            format: 'MM.dd.yyyy'
          }
        }
      },
      controller: ['$scope',
        function($scope) {
          $scope.datepicker = {};

          $scope.datepicker.opened = false;

          $scope.datepicker.open = function($event) {
            $scope.datepicker.opened = !$scope.datepicker.opened;
          };
        }
      ]
    });

    function camelize(string) {
      string = string.replace(/[\-_\s]+(.)?/g, function(match, chr) {
        return chr ? chr.toUpperCase() : '';
      });
      // Ensure 1st char is always lowercase
      return string.replace(/^([A-Z])/, function(match, chr) {
        return chr ? chr.toLowerCase() : '';
      });
    }
  });



  app.controller('MainCtrl', function MainCtrl(formlyVersion) {
    var vm = this;
    // funcation assignment
    vm.onSubmit = onSubmit;

    // variable assignment
    vm.author = { // optionally fill in your info below :-)
      name: 'Kent C. Dodds',
      url: 'https://twitter.com/kentcdodds'
    };
    vm.exampleTitle = 'UI Bootstrap Datepicker'; // add this
    vm.env = {
      angularVersion: angular.version.full,
      formlyVersion: formlyVersion
    };

    vm.model = {
      year: 2005,
      text: 'hello'
    };
    vm.options = {};

    vm.fields = [{
      key: 'year',
      type: 'datepicker',
      templateOptions: {
        label: 'Year',
        type: 'text',
        datepickerPopup: 'dd-MMMM-yyyy',
        datepickerOptions: {
          format: 'yyyy',
          minMode: 'year'
        }
      },
      parsers: [dateToYear],
      formatters: [yearToDate]
    }, {
      key: 'text',
      type: 'input',
      templateOptions: {
        label: 'Text',
      },
      parsers: [toLowerCase],
      formatters: [toUpperCase]
    }];

    vm.originalFields = angular.copy(vm.fields);

    // function definition
    function onSubmit() {
      vm.options.updateInitialValue();
      alert(JSON.stringify(vm.model), null, 2);
    }

    function yearToDate(value) {
      console.log('yearToDate: ' + value);

      if (!value) {
        return new Date();
      }

      return (typeof value === 'object') ? value : (new Date()).setFullYear(value);
    }

    function dateToYear(value) {
      console.log('dateToYear: ' + value);

      return (typeof value === 'object') ? value.getFullYear() : null;
    }

    function toUpperCase(value) {
      console.log('toUpperCase: ' + value);
      return (value || '').toUpperCase();
    }

    function toLowerCase(value) {
      console.log('toLowerCase: ' + value);
      return (value || '').toLowerCase();
    }
  });

})();

body {
  margin: 20px
}
.formly-field {
  margin-bottom: 16px;
}

<!DOCTYPE html>
<html>

<head>
  <!-- Twitter bootstrap -->
  <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">

  <!-- apiCheck is used by formly to validate its api -->
  <script src="//npmcdn.com/api-check@latest/dist/api-check.js"></script>
  <!-- This is the latest version of angular (at the time this template was created) -->
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script>

  <!-- Angular-UI Bootstrap has tabs directive we want -->
  <script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/1.3.2/ui-bootstrap-tpls.js"></script>

  <!-- This is the latest version of formly core. -->
  <script src="//npmcdn.com/angular-formly@latest/dist/formly.js"></script>
  <!-- This is the latest version of formly bootstrap templates -->
  <script src="//npmcdn.com/angular-formly-templates-bootstrap@latest/dist/angular-formly-templates-bootstrap.js"></script>

  <title>Angular Formly Example</title>
</head>

<body ng-app="formlyExample" ng-controller="MainCtrl as vm">
  <div>
    <h1>angular-formly example: {{vm.exampleTitle}}</h1>
    <div>
      This is a <strong>very</strong> basic example of how to use the
      <a href="https://angular-ui.github.io/bootstrap/#/datepicker">UI Boostrap datepicker</a>
      with angular-formly.
    </div>
    <hr />
    <form ng-submit="vm.onSubmit()" name="vm.form" novalidate>
      <formly-form model="vm.model" fields="vm.fields" options="vm.options" form="vm.form">
        <button type="submit" class="btn btn-primary submit-button" ng-disabled="vm.form.$invalid">Submit</button>
        <button type="button" class="btn btn-default" ng-click="vm.options.resetModel()">Reset</button>
      </formly-form>
    </form>
    <hr />
    <h2>Model Value</h2>
    <pre>{{vm.model | json}}</pre>
    <h2>Fields <small>(note, functions are not shown)</small></h2>
    <pre>{{vm.originalFields | json}}</pre>
    <h2>Form</h2>
    <pre>{{vm.form | json}}</pre>
  </div>

  <div style="margin-top:30px">
    <small>
        This is an example for the
        <a href="https://formly-js.github.io/angular-formly">angular-formly</a>
        project made with ♥ by
        <strong>
          <span ng-if="!vm.author.name || !vm.author.url">
            {{vm.author.name || 'anonymous'}}
          </span>
          <a ng-if="vm.author.url" ng-href="{{::vm.author.url}}">
            {{vm.author.name}}
          </a>
        </strong>
        <br />
        This example is running angular version "{{vm.env.angularVersion}}" and formly version "{{vm.env.formlyVersion}}"
      </small>
  </div>

  <!-- Put custom templates here -->
  <script type="text/ng-template" id="datepicker.html">
    <p class="input-group">
      <input type="text" id="{{::id}}" name="{{::id}}" ng-model="model[options.key]" class="form-control" ng-click="datepicker.open($event)" uib-datepicker-popup="{{to.datepickerOptions.format}}" is-open="datepicker.opened" datepicker-options="to.datepickerOptions"
      />
      <span class="input-group-btn">
            <button type="button" class="btn btn-default" ng-click="datepicker.open($event)" ng-disabled="to.disabled"><i class="glyphicon glyphicon-calendar"></i></button>
        </span>
    </p>
  </script>

</body>

</html>
&#13;
&#13;
&#13;

查看控制台日志:第一次格式化程序获取EMPTY值,但必须达到2005(在vm.model中定义)

P.S。 在这个例子中,我注意到了另外一个bug:

初始值datepicker未格式化

我得到Tue May 17 2016 18:25:03 GMT+0300 (EEST)但必须2016

我检查数据贴纸相同的版本没有形式,它工作正常。示例:

&#13;
&#13;
angular.module('ui.bootstrap.demo', ['ngAnimate', 'ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('DatepickerPopupDemoCtrl', function($scope) {
  $scope.dt = '2005-01-31';

  $scope.today = function() {
    $scope.dt = new Date();
  };

  $scope.today();

  $scope.clear = function() {
    $scope.dt = null;
  };

  $scope.inlineOptions = {
    minDate: new Date(),
    showWeeks: true
  };

  $scope.dateOptions = {
    formatYear: 'yy',
    startingDay: 1
  };

  $scope.open1 = function() {
    $scope.popup1.opened = true;
  };

  $scope.open2 = function() {
    $scope.popup2.opened = true;
  };

  $scope.setDate = function(year, month, day) {
    $scope.dt = new Date(year, month, day);
  };

  $scope.popup1 = {
    opened: false
  };

  $scope.popup2 = {
    opened: false
  };
});
&#13;
body {
  padding: 20px;
}
&#13;
<!doctype html>
<html ng-app="ui.bootstrap.demo">

<head>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.js"></script>
  <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-1.3.2.js"></script>
  <script src="example.js"></script>
  <link href="//netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>

  <div ng-controller="DatepickerPopupDemoCtrl">
    <pre>Selected date is: <em>{{dt | date:'fullDate' }}</em></pre>

    <h4>Popup</h4>
    <div class="row">
      <div class="col-md-6">
        <p class="input-group">
          <input type="text" class="form-control" uib-datepicker-popup="MMM dd, yyyy" ng-model="dt" is-open="popup1.opened" datepicker-options="dateOptions" ng-required="true" close-text="Close" />
          <span class="input-group-btn">
            <button type="button" class="btn btn-default" ng-click="open1()"><i class="glyphicon glyphicon-calendar"></i></button>
          </span>
        </p>
      </div>

      <div class="col-md-6">
        <p class="input-group">
          <input type="text" class="form-control" uib-datepicker-popup ng-model="dt" is-open="popup2.opened" datepicker-options="dateOptions" ng-required="true" close-text="Close" />
          <span class="input-group-btn">
            <button type="button" class="btn btn-default" ng-click="open2()"><i class="glyphicon glyphicon-calendar"></i></button>
          </span>
        </p>
      </div>
    </div>
    <hr />
    <button type="button" class="btn btn-sm btn-info" ng-click="today()">Today</button>
    <button type="button" class="btn btn-sm btn-default" ng-click="setDate(2009, 7, 24)">2009-08-24</button>
    <button type="button" class="btn btn-sm btn-danger" ng-click="clear()">Clear</button>

  </div>
</body>

</html>
&#13;
&#13;
&#13;

我认为格式化程序在模板初始化时没有第一次调用。

输入[type = number]的示例,如果初始值是字符串,则抛出错误:

&#13;
&#13;
/* global angular */
(function() {

  'use strict';

  var app = angular.module('formlyExample', ['formly', 'formlyBootstrap', 'ui.bootstrap']);

  app.run(function(formlyConfig) {
    var attributes = [
      'date-disabled',
      'custom-class',
      'show-weeks',
      'starting-day',
      'init-date',
      'min-mode',
      'max-mode',
      'format-day',
      'format-month',
      'format-year',
      'format-day-header',
      'format-day-title',
      'format-month-title',
      'year-range',
      'shortcut-propagation',
      'datepicker-popup',
      'show-button-bar',
      'current-text',
      'clear-text',
      'close-text',
      'close-on-date-selection',
      'datepicker-append-to-body'
    ];

    var bindings = [
      'datepicker-mode',
      'min-date',
      'max-date'
    ];

    var ngModelAttrs = {};

    angular.forEach(attributes, function(attr) {
      ngModelAttrs[camelize(attr)] = {
        attribute: attr
      };
    });

    angular.forEach(bindings, function(binding) {
      ngModelAttrs[camelize(binding)] = {
        bound: binding
      };
    });

    formlyConfig.setType({
      name: 'datepicker',
      templateUrl: 'datepicker.html',
      wrapper: ['bootstrapLabel', 'bootstrapHasError'],
      defaultOptions: {
        ngModelAttrs: ngModelAttrs,
        templateOptions: {
          datepickerOptions: {
            format: 'MM.dd.yyyy'
          }
        }
      },
      controller: ['$scope',
        function($scope) {
          $scope.datepicker = {};

          $scope.datepicker.opened = false;

          $scope.datepicker.open = function($event) {
            $scope.datepicker.opened = !$scope.datepicker.opened;
          };
        }
      ]
    });

    function camelize(string) {
      string = string.replace(/[\-_\s]+(.)?/g, function(match, chr) {
        return chr ? chr.toUpperCase() : '';
      });
      // Ensure 1st char is always lowercase
      return string.replace(/^([A-Z])/, function(match, chr) {
        return chr ? chr.toLowerCase() : '';
      });
    }
  });



  app.controller('MainCtrl', function MainCtrl(formlyVersion) {
    var vm = this;
    // funcation assignment
    vm.onSubmit = onSubmit;

    // variable assignment
    vm.author = { // optionally fill in your info below :-)
      name: 'Kent C. Dodds',
      url: 'https://twitter.com/kentcdodds'
    };
    vm.exampleTitle = 'UI Bootstrap Datepicker'; // add this
    vm.env = {
      angularVersion: angular.version.full,
      formlyVersion: formlyVersion
    };

    vm.model = {
      year: 2005,
      text: 'hello',
      number: '123.4'
    };
    vm.options = {};

    vm.fields = [{
      key: 'year',
      type: 'datepicker',
      templateOptions: {
        label: 'Year',
        type: 'text',
        datepickerPopup: 'dd-MMMM-yyyy',
        datepickerOptions: {
          format: 'yyyy',
          minMode: 'year'
        }
      },
      parsers: [dateToYear],
      formatters: [yearToDate]
    }, {
      key: 'text',
      type: 'input',
      templateOptions: {
        label: 'Text',
      },
      parsers: [toLowerCase],
      formatters: [toUpperCase]
    }, {
      key: 'number',
      type: 'input',
      templateOptions: {
        label: 'Number',
        type: 'number'
      },
      formatters: [strToNumber]
    }];

    vm.originalFields = angular.copy(vm.fields);

    // function definition
    function onSubmit() {
      vm.options.updateInitialValue();
      alert(JSON.stringify(vm.model), null, 2);
    }

    function yearToDate(value) {
      console.log('yearToDate: ' + value);

      if (!value) {
        return new Date();
      }

      return (typeof value === 'object') ? value : (new Date()).setFullYear(value);
    }

    function dateToYear(value) {
      console.log('dateToYear: ' + value);

      return (typeof value === 'object') ? value.getFullYear() : null;
    }

    function toUpperCase(value) {
      console.log('toUpperCase: ' + value);
      return (value || '').toUpperCase();
    }

    function toLowerCase(value) {
      console.log('toLowerCase: ' + value);
      return (value || '').toLowerCase();
    }

    function strToNumber(value) {
      console.log('strToNumber: ' + value);
      return parseFloat(value);
    }
  });

})();
&#13;
body {
  margin: 20px
}
.formly-field {
  margin-bottom: 16px;
}
&#13;
<!DOCTYPE html>
<html>

<head>
  <!-- Twitter bootstrap -->
  <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">

  <!-- apiCheck is used by formly to validate its api -->
  <script src="//npmcdn.com/api-check@latest/dist/api-check.js"></script>
  <!-- This is the latest version of angular (at the time this template was created) -->
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script>

  <!-- Angular-UI Bootstrap has tabs directive we want -->
  <script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/1.3.2/ui-bootstrap-tpls.js"></script>

  <!-- This is the latest version of formly core. -->
  <script src="//npmcdn.com/angular-formly@latest/dist/formly.js"></script>
  <!-- This is the latest version of formly bootstrap templates -->
  <script src="//npmcdn.com/angular-formly-templates-bootstrap@latest/dist/angular-formly-templates-bootstrap.js"></script>

  <title>Angular Formly Example</title>
</head>

<body ng-app="formlyExample" ng-controller="MainCtrl as vm">
  <div>
    <h1>angular-formly example: {{vm.exampleTitle}}</h1>
    <div>
      This is a <strong>very</strong> basic example of how to use the
      <a href="https://angular-ui.github.io/bootstrap/#/datepicker">UI Boostrap datepicker</a>
      with angular-formly.
    </div>
    <hr />
    <form ng-submit="vm.onSubmit()" name="vm.form" novalidate>
      <formly-form model="vm.model" fields="vm.fields" options="vm.options" form="vm.form">
        <button type="submit" class="btn btn-primary submit-button" ng-disabled="vm.form.$invalid">Submit</button>
        <button type="button" class="btn btn-default" ng-click="vm.options.resetModel()">Reset</button>
      </formly-form>
    </form>
    <hr />
    <h2>Model Value</h2>
    <pre>{{vm.model | json}}</pre>
    <h2>Fields <small>(note, functions are not shown)</small></h2>
    <pre>{{vm.originalFields | json}}</pre>
    <h2>Form</h2>
    <pre>{{vm.form | json}}</pre>
  </div>

  <div style="margin-top:30px">
    <small>
        This is an example for the
        <a href="https://formly-js.github.io/angular-formly">angular-formly</a>
        project made with ♥ by
        <strong>
          <span ng-if="!vm.author.name || !vm.author.url">
            {{vm.author.name || 'anonymous'}}
          </span>
          <a ng-if="vm.author.url" ng-href="{{::vm.author.url}}">
            {{vm.author.name}}
          </a>
        </strong>
        <br />
        This example is running angular version "{{vm.env.angularVersion}}" and formly version "{{vm.env.formlyVersion}}"
      </small>
  </div>

  <!-- Put custom templates here -->
  <script type="text/ng-template" id="datepicker.html">
    <p class="input-group">
      <input type="text" id="{{::id}}" name="{{::id}}" ng-model="model[options.key]" class="form-control" ng-click="datepicker.open($event)" uib-datepicker-popup="{{to.datepickerOptions.format}}" is-open="datepicker.opened" datepicker-options="to.datepickerOptions"
      />
      <span class="input-group-btn">
            <button type="button" class="btn btn-default" ng-click="datepicker.open($event)" ng-disabled="to.disabled"><i class="glyphicon glyphicon-calendar"></i></button>
        </span>
    </p>
  </script>

</body>

</html>
&#13;
&#13;
&#13;

issue

中描述的问题也是如此

也许有人可以帮助我。

感谢您的帮助。

0 个答案:

没有答案