我在这里有一项艰巨的任务。我正在开发一个AngularJS
Web应用程序,该应用程序能够向我们项目的Restful Web Service
发送不同的HTTP方法并以JSON接收响应。基本上看起来像这样:
您可以从此应用程序中创建一些REST resource
。假设exam
。要创建考试-您可以从可用资源列表中选择一种资源。这将触发一个函数,该函数向localhost:8080/STEP/api/explain/resorceName
发送请求并获取此资源的描述。说明如下:
http://jsonblob.com/534fc022e4b0bb44248d6460
收到响应后-我开始构建如下输入字段(allFields
-此资源的字段对象数组,enumValues
-资源的字段的枚举值(如果属性为isEnum = true
)):
<div ng-repeat="field in allFields">
<div ng-show={{!field.isEnum}}>
<p ng-show={{field.isRequired}}>{{field.name}}*: </p>
<p ng-show={{!field.isRequired}}>{{field.name}}: </p>
<input type="text" ng-model="updateEntityResource[field.name]" ng-change="getUpdateEntityAsText()"
class="form-control" placeholder="{{parseClassName(field.type)}}">
</div>
<div ng-show={{field.isEnum}}>
<p ng-show={{field.isRequired}}>{{field.name}}*: </p>
<p ng-show={{!field.isRequired}}>{{field.name}}: </p>
<select ng-model="updateEntityResource[field.name]" ng-change="getUpdateEntityAsText()" class="form-control">
<option></option>
<option ng-repeat="enumValue in field.enumValues" label={{enumValue.name}}>{{enumValue.ordinal}}</option>
</select>
</div>
</div>
现在,问题了。我需要创建一个递归指令,该指令将能够以上述方式为“ restResourceName”不为null的每个资源字段生成字段。要获取所有字段,您只需向本地主机发送请求:8080 / STEP / api / explain / restResourceName,并获得类似上述的JSON响应,然后将其用于构建HTML元素以将值输入模型。
如何使用角度递归指令来实现?
最佳答案
我认为您在正确的轨道上。我创建了a small plunkr,它基于js对象中的描述生成表单。
index.html:
<body ng-controller="MainCtrl">
<div my-form form-config="allFields" model="model1"></div>
<div my-form form-config="allFields" model="model2"></div>
Model 1: {{model1|json}}<br>
Model 2: {{model2|json}}<br>
</body>
myForm.html(模板):
<div ng-repeat="field in formConfig">
<div ng-show={{!field.isEnum}}>
<p ng-show={{field.isRequired}}>{{field.name}}*: </p>
<p ng-show={{!field.isRequired}}>{{field.name}}: </p>
<input type="text" ng-model="model[field.name]">
</div>
</div>
JS:
app.controller('MainCtrl', function($scope) {
$scope.allFields = [
{
"isEnum": false,
"isRequired": true,
"name": "First name"
},
{
"isEnum": false,
"isRequired": false,
"name": "Last name"
}
];
$scope.model1 = {};
$scope.model2 = {"First name":"John","Last name":"Doe"};
});
app.directive('myForm', function() {
return {
scope: {
formConfig:"=",
model:"="
},
templateUrl:"myForm.html",
};
});
你到底坚持了什么?
关于javascript - 带有动态HTML模板的AngularJS递归指令,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23132779/