使用带有angularjs的json模式动态生成表单

时间:2017-06-14 11:09:59

标签: angularjs json angularjs-directive

我有一个json架构,如下所示:

var schema = {
    "type": "object",
    "properties": {
        "requestedFor": {
            "type": "string"
        },
        "location": {
            "type": "string"
        },
        "shortDescription":{
            "type": "string"
        },
        "description": {
            "type": "string"
        }
    }
};


var options = {
    "fields": {
        "requestedFor": {
            "requestedFor": "text",
            "label": "*Name"
        },
        "location": {
            "type": "text",
            "label": "*Location"
        },
        "shortDescription":{
            "type": "text",
            "label": "Short Description"
        },
        "description": {
            "type": "textarea",
            "label": "Description",
            "rows": 5,
            "cols": 60,
            "label": "",
            "wordlimit": 250
        }
    },
    "form": {
        "attributes": {
            "method": "POST",
            "action": "#",
            "enctype": "multipart/form-data"
        },
        "buttons": {
            "submit": {
                "value": "Submit"
            }
        }
    }
};

所以我想使用这个json模式使用angularjs动态创建自定义指令。所以为此我创建了类似下面的代码:

var app = angular.module("app", [])
  .directive("wrapper", function($compile, $interval) {
    return {
      scope: {
        directiveName: "="
      },
      link: function(scope, elem, attrs) {
        scope.$watch("directiveName", function() {
          var html = "<" + scope.directiveName + "></" + scope.directiveName + ">";
          elem.html(html);
          $compile(elem.contents())(scope);
        });
      }
    }
  }).controller("addDirectives", function($scope, $interval) {
    let directiveNames = ['d1', 'd2', 'd3', "d4"];
    $scope.directiveName = directiveNames[0];

  }).directive("d1", function() {
    return {
      template: "<input type='text'>Requested For</input>"
    }
  }).directive("d2", function() {
    return {
      template: "<input type='text'>Location</input>"
    }
  }).directive("d3", function() {
    return {
      template: "<input type='text'>Short Description</input>"
    }
  }).directive("d4", function(){
      return {
          template: "<input type='textarea'>Description</input>"
      }
  })

这里我的目的是使用这个json模式动态生成表单,因为我有很多可用的json文件,所以我需要创建不同的自定义指令。

<!DOCTYPE html>
<html ng-app="app">
<head>
<body ng-controller="addDirectives">

    <div class="container">

        <div class="row">
            <div class="col-md-12">

                <div id="form"></div>

            </div>
        </div>
    </div>

</body>
</html>

那么有人可以为此提供任何解决方案吗?

0 个答案:

没有答案
相关问题