gpt4 book ai didi

javascript - 具有动态 HTML 模板的 AngularJS 递归指令

转载 作者:行者123 更新时间:2023-11-30 17:30:40 24 4
gpt4 key购买 nike

我这里有一个非常艰巨的任务。我正在开发一个 AngularJS 网络应用程序,它能够向我们项目的 Restful Web 服务 发送不同的 HTTP 方法并接收 JSON 格式的响应。基本上它看起来像这样:

enter image description here

您可以从此应用程序创建一些 REST 资源。比方说一个考试。要创建考试 - 您可以从可用资源列表中选择一个资源。这会触发一个函数,该函数向 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”不为空的每个资源字段生成字段。要获得它的所有字段,您只需向 localhost:8080/STEP/api/explain/restResourceName 发送请求并获得如上所示的类似 JSON 响应,然后用于构建 HTML 元素以将值输入模型。

如何使用 Angular 递归指令实现这一点?

最佳答案

我认为您走在正确的轨道上。我创建了 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com