Angular Formly - 从控制器生成模型的自定义类型

时间:2016-09-21 08:11:02

标签: angularjs angular-formly

我一整天都在寻找实现这一目标的方法,任何帮助都会非常感激。 我们想要创建一个日期选择器,但不是使用javascript Date格式而是使用字符串'YYYY-MM-DD'。所以我们尝试创建一个自定义类型,它有两个输入,一个type =“date”,这样用户就可以引入他想要的日期,一个隐藏的类型=“text”来存储实际的模型。 它看起来很好:

formlyConfig.setType({
  'name': 'nativeDateSelect',
  template: `
    <input type="text" class="form-control" style="display: none;"
      ng-model="model[options.key]" />

    <input type="date" class="form-control"
      ng-model="dateValue"
      formly-skip-ng-model-attrs-manipulator />
  `,
  wrapper: ['bootstrapLabel', 'bootstrapHasError'],
  controller: function ($scope, moment) {
    $scope.dateValue = null;

    $scope.$watch('model[options.key]', function (newValue) {
      if (angular.equals($scope.dateValue, moment(newValue).toDate())) return;
      $scope.dateValue = moment(newValue).toDate();
    });

    $scope.$watch('dateValue', function (newValue) {
      if (angular.equals($scope.model[$scope.options.key], moment(newValue).format('YYYY-MM-DD'))) return;
      $scope.model[$scope.options.key] = moment(newValue).format('YYYY-MM-DD');
    });
  },
  'defaultOptions': {
    'extras': {
      'validateOnModelChange': true
    }
  }
});

就是这样,它确实有效,改变任何输入都会修改另一个。

但问题是,一旦我以实际形式介绍此类型并尝试使用它,比如添加一个onChange函数,它就不会触发,因为我没有对文本输入进行更改

/* global angular */
(function() {
  
  'use strict';

  var app = angular.module('formlyExample', ['formly', 'formlyBootstrap', 'angularMoment'], function config(formlyConfigProvider) {
    // set templates here
    formlyConfigProvider.setType([
      {
        'name': 'nativeDateSelect',
      template: 
        '<input type="text" class="form-control" style="display: block;" ' +
          'ng-model="model[options.key]" /> ' +
        '<input type="date" class="form-control" ' +
          'ng-model="dateValue" ' +
          'formly-skip-ng-model-attrs-manipulator />',
      wrapper: ['bootstrapLabel', 'bootstrapHasError'],
      controller: function ($scope, moment) {
        $scope.dateValue = null;

        $scope.$watch('model[options.key]', function (newValue) {
          if (angular.equals($scope.dateValue, moment(newValue).toDate())) return;
          $scope.dateValue = moment(newValue).toDate();
        });

        $scope.$watch('dateValue', function (newValue) {
          if (angular.equals($scope.model[$scope.options.key], moment(newValue).format('YYYY-MM-DD'))) return;
          $scope.model[$scope.options.key] = moment(newValue).format('YYYY-MM-DD');
        });
      },
      'defaultOptions': {
        'extras': {
          'validateOnModelChange': true
        }
      }
      }
    ]);
  });
  

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

    vm.exampleTitle = 'Default Options'; // add this

    vm.model = {};
    
    vm.fields = [
      {
        'type': 'nativeDateSelect',
        'key': 'startDate',
        'expressionProperties': {
          'templateOptions.label': '\'startDate\''
        },
        'templateOptions': {
          'required': true,
          'onChange': function (modelValue, field, scope) {
            alert('startDate: ' + modelValue);
          }
        }
      }
    ];
    
    vm.originalFields = angular.copy(vm.fields);

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

})();
<!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.4.7/angular.js"></script>

    <!-- This is the current state of master for formly core. -->
    <script src="//npmcdn.com/angular-formly@latest/dist/formly.js"></script>
    <!-- This is the current state of master for the bootstrap templates -->
    <script src="//npmcdn.com/angular-formly-templates-bootstrap@latest/dist/angular-formly-templates-bootstrap.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-moment/0.10.3/angular-moment.min.js"></script>
    
    <title>Angular Formly Example</title>
  </head>

  <body ng-app="formlyExample" ng-controller="MainCtrl as vm">
    <div>
      <h1>Changing our model from the controller</h1>
      <hr />
      <form ng-submit="vm.onSubmit()" novalidate>
        <formly-form model="vm.model" fields="vm.fields" form="vm.form">
          <button type="submit" class="btn btn-primary submit-button">Submit</button>
        </formly-form>
      </form>
      <h2>Model</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>

  </body>

</html>

有谁知道如何管理这样的场景?我需要一个输入来实际输入而另一个输入是模型,所以这个应该跟踪更改/验证/等。无论何时修改。

再次感谢!

0 个答案:

没有答案