angular-formly入门例子代码解析(一)

前文 简要介绍了angular-formly,本文对angular-formly的 入门例子 的代码做一个初步注解。在这个例子中,一共有六个表单项,展示了angular-formly的一些特点。

首先看如何引用这个库。HTML代码中的head部分,引用了一些必要的库,包括bootstrap(仅CSS部分), api-check, angular, angular-formly, angular-formly-templates-bootstrap, 如下:

<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>
 <title>Angular Formly Example</title>
</head>

JS代码中,顶层的Angular模块依赖:

var app = angular.module('formlyExample', ['formly', 'formlyBootstrap'], function config(formlyConfigProvider) {
 // set templates here
 formlyConfigProvider.setType({
   name: 'custom',
   templateUrl: 'custom.html'
 });
});

这个例子中顶层模块依赖了 formly和formlyBootstrap这两个module,formly是必须的,formlyBootstrap是Bootstrap特定的模板。config函数这里暂时忽略。

其次看看如何构造一个最小的formly应用。核心的HTML模版代码如下:

<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>

angular-formly最主要就是提供了 formlyForm这个directive,包含4个属性,其中,model和fields是必须的,model属性是指向controller里面所有表单项对应的变量(双向绑定变量)的父对象,fields属性对应controller里面的一个数组,该数组中每一个元素对应一个逻辑表单项。这里对照下controller中的关键代码:

vm.model = {
  awesome: true
};

vm.fields = [
  {
    key: 'text',
    type: 'input',
    templateOptions: {
      label: 'Text',
      placeholder: 'Formly is terrific!'
    }
  },
  /** 其他fields目前省略 */
];

换言之,根据目前摘出来的代码,我们可以期待目标程序会包含一个表单项,类型为 <input type="text"> ,与控制器中的 vm.model.text 变量绑定。这里可以把这个例子更加简化一些, html中的模板代码只需要写成:

<formly-form model="vm.model" fields="vm.fields" >
</formly-form>

在这个基础上,只要在controller代码中扩充vm.fields数组,就定义了更多的表单项,而这个特性,恰恰是angular-formly最让人喜欢使用的原因。本文到此结束,更多代码解析,等我再写。