如何使用角度从 json 制作视图(表单)? [英] how to make view (form)from json using angular?
问题描述
我正在尝试从 json 中创建视图.当我有对象数组时.我能够创建视图并验证该视图.如果我有这个对象数组,在那种情况下我可以查看,检查 plunkerhttp://plnkr.co/edit/eD4OZ8nqETBACpSMQ7Tm?p=preview
I am trying to make view from json .When I have array of objects .I am able to make view and validate that view . If I have this array of object ,in that case I make able to view , check plunker http://plnkr.co/edit/eD4OZ8nqETBACpSMQ7Tm?p=preview
[{
type: "email",
name: "email",
required:true
}, {
type: "text",
name: "name",
required:true
}, {
type: "number",
name: "phonenumber",
required:true
}, {
type: "checkbox",
name: "whant to check"
},
{
type: "url",
name: "server Url"
}];
现在当我有 json 对象时出现问题.我需要从 json 对象显示视图.我不知道从哪里开始工作我有这个 json
Now the problem occurred when i have json object .I need to show view from json object .I don't know from where I will start work I have this json
- "displayName": 显示来自输入文本的标签名称领域.
- inputValues :表示tmput填充的类型.如果是数字则用户只填写号码,文本然后用户只填写号码,然后电子邮件用户填写电子邮件,如果切换,则使用给定的下拉列表选项.
- required"给出是否需要字段?
推荐答案
假设您的 JSON
来自配置文件或服务,您可以从获取 JSON
开始> 作为 JSON
对象:
Assuming your JSON
is coming from a configuration file or a service, you can start by obtaining the JSON
as a JSON
object:
angular.module('myapp', [])
.controller('MyController', ['$scope', function($scope) {
$scope.outputs = {};
$scope.rawInput = JSON.parse( '{"studentName": "abc",
"input": {
"loginUser": {
"displayDetail": "UserId for login.",
"displayName": "Login User Id*",
"inputType": "TEXT",
(我不得不转义返回以允许解析漂亮的打印JSON
字符串)
(I had to escape returns to allow the pretty printed JSON
string to be parsed)
一旦你有了它,你就快到了.现在您可以进入您需要的 JSON
级别并构建您的 inputs
数组:
Once you have that, you are nearly there. Now you can just go the level of JSON
that you require and construct your inputs
array:
$scope.formInputs = $scope.rawInput['input'];
$scope.inputs = [];
angular.forEach($scope.formInputs, function(value, key) {
/* do something for all key: value pairs */
$scope.inputs.push({"type":value.inputType.toLowerCase(),"name":value.name,"required": value.required})
});
请注意,您可能应该在这里进行一些错误检查 - 就本示例而言,我不使用任何错误检查.这里是演示此代码的工作 plnkr.
Note you should probably do some error checking here - for the purposes of this example, I don't use any. Here is a working plnkr that demonstrates this code.
我还没有完成所有工作 - 您必须构建选择或单选按钮输入,但我认为您应该可以从这里获取它.
I haven't got it all to work - you'll have to construct your select or radio button inputs, but I think you should be able to take it from here.
编辑我已经取消了 plnkr 的日期以使其公开
EDIT I have undated the plnkr to make it public
这篇关于如何使用角度从 json 制作视图(表单)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!