Skip to content

Usage: JSON Schema Forms

Callan Milne edited this page Jun 21, 2017 · 6 revisions

Inspired by schemaform

Try the demo on Codepen.io

HTML

<section ng-controller="FormContainerCtrl as $f">
  <form id="UserSubmission"
    ab-schema="$f.schema"
    ab-form="$f.form"
    ab-model="$f.model"
    layout="column">
  </form>
</section>

JavaScript

Option 1: In-line schema

const MyApp = angular.module("MyApp", [
  "AppBuilder3"
]);

MyApp.controller("FormContainerCtrl", FormContainerCtrl);

FormContainerCtrl.$inject = ["JsonSchema"];
function FormContainerCtrl (  JsonSchema) {

  const $f = this;

  $f.schema = new JsonSchema({
    "$schema": "http://json-schema.org/draft-04/schema#",
    "description": "schema for a person",
    "type": "object",
    "additionalProperties": false,
    "required": [ "id", "full_name", "date_added", "is_online" ],
    "properties": {
      "id": {
        "type": "string",
        "description": "The Person's v4 UUID",
        "format": "uuid"
      },
      "full_name": {
        "type": "string",
        "description": "E.g. 'Max Power'",
        "maxLength": 255
      },
      "date_added": {
        "type": "string",
        "format": "date-time"
      },
      "is_online": {
        "type": "boolean",
        "value": false
      }
    }
  });

  $f.form = [
    "*",
    {
      type: "submit",
      title: "Save"
    }
  ];

  $f.model = {};

}

Option 2: Remote schema

const MyApp = angular.module("MyApp", [
  "AppBuilder3"
]);

MyApp.controller("FormContainerCtrl", FormContainerCtrl);

FormContainerCtrl.$inject = ["JsonSchema"];
function FormContainerCtrl (  JsonSchema) {

  const $f = this;

  $f.schemaUrl = _schemaUrl("v1/product.json#");

  $f.schema = {};

  $f.form = [
    "*",
    {
      type: "submit",
      title: "Save"
    }
  ];

  $f.model = {};

  loadSchema();

  function loadSchema () {
    JsonSchema.load($f.schemaUrl)
      .then(function (res) {
        $timeout(function () {
          $f.schema = res;
        });
      })
      .catch(err => {
        console.log(err);
      });
  }

  function _schemaUrl (schemaId) {
    return "https://raw.githubusercontent.com" +
      "/eviratec/schema/master/" + schemaId;
  }

}