如何使用json在角度js中构建动态控件?

时间:2015-05-20 14:35:43

标签: html json angularjs dynamic controls

我正在开展一个角度js项目。现在控件是静态的。但客户希望基于数据库创建html控件。

我有一个包含控件规范的表

例如:

输入: text / dropdown / radio / checkbox

事件: onchange / onblur / onfocus

属性: “颜色:红”

如何生成可以将数据库值解析为html控件的动态模型?

任何帮助都会非常感激......

1 个答案:

答案 0 :(得分:3)

使用ng-repeat指令非常简单。请注意我如何将模型的值分配回ng-repeat中的范围变量。这允许我稍后检索它。

angular.module('formModule', []).
controller('DynamicFormController', ['$scope',
  function($scope) {

    //Set equal to json from database
    $scope.formControls = [{
        name: "Name",
        type: "text"
      }, {
        name: "Age",
        type: "number",
        color: "red"
      },

      {
        name: "UseNestedControls",
        type: "checkbox",
        nestCondition: true,
        nestedControls: [{
          name: "NestedText",
          type: "text"
        }]
      }
    ];


  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="formModule">
  <div ng-controller="DynamicFormController">
    <form>
      <div ng-repeat="input in formControls">
        <label>{{input.name}}</label>
        <input type="{{input.type}}" ng-model="input.value" ng-style="{'color':input.color}" />
        <div ng-repeat="nestedInput in input.nestedControls" style="margin-left:20px" ng-show="input.value == input.nestCondition">
          <label>{{nestedInput.name}}</label>
          <input type="{{nestedInput.type}}" ng-model="nestedInput.value" ng-style="{'color':nestedInput.color}"/>
        </div>
      </div>
    </form>
    <div ng-repeat="input in formControls">
      <span>{{input.name}} = {{input.value}}</span>
      <div  ng-repeat="nestedInput in input.nestedControls" style="margin-left:20px">
        <span>{{nestedInput.name}} = {{nestedInput.value}}</span>
        </div>
    </div>
  </div>
</body>