how to make view (form)from json using angular?

家住魔仙堡 提交于 2019-12-17 20:56:25

问题


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"
            }];

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": display the name of label which is from of input text field.
  • inputValues :represent the type of tmput filled .if it is number then user fill only number , text then user only fill number ,email then user fill email , if it switch then it is drop down with given option.
  • "required" give if field is required or not ?

回答1:


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",\

(I had to escape returns to allow the pretty printed JSON string to be parsed)

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})
});

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.

EDIT I have undated the plnkr to make it public



来源:https://stackoverflow.com/questions/25217933/how-to-make-view-formfrom-json-using-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!