【问题标题】:Adding the input fields dynamically from nested json object in angulajs从angularjs中的嵌套json对象动态添加输入字段
【发布时间】:2017-04-10 08:19:08
【问题描述】:
 var inputs={
    'firstname': '',
    'lastName':'',
   'account':{
     'role':'',
     'status':''
   }
 }

这是我的模型数组。我想在网页中动态显示它,并通过修改 json 数组,更改也会影响表单。

这是图片

【问题讨论】:

  • 使用 $scope 或角度模型 {{model}}
  • 你能分享一下代码吗

标签: angularjs arrays json


【解决方案1】:

统一更新: 对于您的情况,您可以使用ng-switch 根据条件生成元素。


注意事项(已包含在代码 sn-p 中): ng-repeat 将生成它自己的scope,因此除非您将其与original scope 绑定,否则您的模型不会更新。参考here.


旧答案: 使用ng-model 实现two-way-databinding。 参考下面的代码sn-p:

angular.module("app", []).controller("myCtrl", function($scope) {
  $scope.inputs = {
    'firstname': 'test first name',
    'lastName': 'test last name',
    'account': {
      'role': 'test role',
      'status': 'test status'
    }
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.4/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
  <!-- First Name: <input type="text" ng-model="inputs.firstname"><br>     
       Last Name: <input type="text" ng-model="inputs.lastName"><br>        Account Role: <input type="text" ng-model="inputs.account.role"><br> 
       Account Status: <input type="text" ng-model="inputs.account.status"><br> -->
  <div ng-repeat="(key1, value) in inputs" ng-switch="key1">
    <div ng-switch-when="account">
      <div ng-repeat="(key2, value2) in value">
        {{key1 | uppercase}} => {{ key2 | uppercase}}
        <input type="text" ng-model="inputs[key1][key2]">
      </div>
    </div>
    <div ng-switch-default>
      {{key1 | uppercase}}
      <input type="text" ng-model="inputs[key1]">
    </div>
  </div>
  {{inputs}}
</div>

【讨论】:

  • 它不应该是这样的......看到数组包含内部数组,我不能在这里使用输入字段它应该从 json 数组模型自动创建
  • @DeepakVijay 你的意思是object 包含内部object
  • 是的,该对象包含内部对象及其嵌套的 json 数组..它应该检查每次数组值..如果它是一个内部数组,它应该打印它..我们不应该使用每次创建输入字段的代码
  • 是的,该对象包含内部对象及其嵌套的 json 数组..它应该检查每次数组值..如果它是一个内部数组,它应该打印它..我们不应该使用每次创建输入字段的代码
  • 【解决方案2】:

    /我的 html 应该是这样的/

      <head>
        <script data-require="angular.js@1.4.1" data-semver="1.4.1" src="https://code.angularjs.org/1.4.1/angular.js"></script>
        <script src="script.js"></script>
      </head>
    
      <body ng-controller="MainCtrl">
    
    
        <script type="text/ng-template" id="tree-structure">
        <label>{{dt}}</label><input type="text" name="" value="{{dt.label}}">
         <ul class="childElement">
            <li ng-repeat="dt in dt.nodes" ng-include="'tree-structure'">
            </li>
         </ul>
    </script>
    
    <ul class="parentList">
        <li ng-repeat="(key, value) in inputs" >
            <div  ng-repeat="(key1, value1) in value">
                <label>{{key1}}</label>
                <input type="text" name="" value="{{value1}}">
    
               <!--  <div ng-repeat="(key2, value2) in value1">
                  <label>{{key2}}</label><input type="text" name="" value="{{value2}}"> 
                </div> -->
    
            </div>
            <div ></div>
        </li>
    
        </div>
    </ul>
      </body>
    
    </html>
    

    【讨论】:

    • 您应该在问题中添加详细信息,而不是在这里回答。
    【解决方案3】:

    一些观察:

    • 您的JSON 应使用字段的type 正确格式化。
    • 如果您想以form fields 的形式访问object properties,那么它的结构应该很好,以便我们也可以动态添加字段的类型。

      [{
          name: 'firstName',
          type: 'text'
      }, {
          name: 'lastname',
          type: 'text'
      }, {
          account: [{
              name: 'role',
              type: 'text'
          }, {
              name: 'status',
              type: 'text'
          }]
      }]
      
    • 因为你的JSONnested objects。因此,首先递归迭代它并创建one dimensional 数组,然后使用1D 数组创建字段。

    演示

    var myApp = angular.module('myApp',[]);
    
    myApp.controller('MyCtrl', function($scope) {
        var inputs = [{
    	name: 'firstName',
    	type: 'text'
    }, {
    	name: 'lastname',
    	type: 'text'
    }, {
    	account: [{
    		name: 'role',
    		type: 'text'
    	}, {
    		name: 'status',
    		type: 'text'
    	}]
    }];
    
    $scope.fields = [];
    function structuredObj(obj) {
      for (var i in obj) {
         if (obj[i].type == 'text') {
           $scope.fields.push(obj[i]);
         } else {
           structuredObj(obj[i])
         }
      }
    };
    
    structuredObj(inputs);
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="myApp" ng-controller="MyCtrl">
    <form name="myForm" novalidate>
      <div ng-repeat="item in fields" class="form-group">
            <input
                name="item.name"
                type="{{ item.type }}"
                placeholder="{{ item.name }}"
                ng-model="item.value"
                required />
      </div>
    <button ng-disabled="myForm.$invalid">Submit</button>
    </form>
    </div>

    【讨论】:

    • 您使用了 2 ng-repeats ..这将适用于 2-dimension ..如果在 3D 和 4d 的情况下以及更多..我需要解决方案..我想要解决方案对于可以从任何 json 数组(嵌套 Json)动态生成的任意数量的字段
    • @DeepakVijay 我更新了答案。你现在可以检查了。
    • :- 请按格式提供答案。我需要添加标签,子数组应显示为带箭头的子数组..
    • 这件小事你也可以自己做。我不能把你盘子里的所有东西都给我。
    【解决方案4】:
    <div ng-repeat="(key1, value1) in myPersonObj">
        <div ng-repeat="(key, value) in value1">
            <label>{{key}}</label>
            <input type="text" name="" value="{{value}}">
        </div>
    </div>
    

    var app = angular.module("test",[]);
    
    app.controller("MainCtrl",function($scope){
    
      $scope.inputs = [
        {
          "firstname" : "Test"
        },{
          "lastname" : "Test1"
        },{                           
          "Account" : [
    
            {"role" : "Test3"},
            {"status" : "Test4"},
          ]
        },
        {
          "Account1" : [
    
            {"role" : "Test3"},
            {"status" : "Test4"},
          ]
        },
        {
          "Account2" : [
    
            {"role" : {
              'dim3': {
                'dim4':{
                  'dim5':'cccc'
                }
              }
            }
    
          },
            {"status" : "Test4"},
          ]
        }
      ];
    $scope.person = [];
    $scope.myPersonObj = [];
    /*console.log($scope.keys(inputs));*/
        $scope.checkIndex1 = function(arg, myPersonObj)
        {
            if (angular.isArray(arg) || angular.isObject(arg)) {
                angular.forEach(arg, function (value, key) {
                    console.log(value);
                    if(angular.isObject(value) || angular.isArray(value))
                    {
                        $scope.checkIndex1(value, myPersonObj);
                    }
                    else
                    {
                        console.log("pushing");
                        myPersonObj.push(arg);
                    }
                });
            }
            else
            {
                console.log("pushing1");
                myPersonObj.push(arg);
            }      
        }
    
        $scope.checkIndex1($scope.inputs, $scope.myPersonObj);
    
        console.log("myPersonObj :"+ JSON.stringify($scope.myPersonObj));
    
        console.log($scope.inputs);
    

    【讨论】:

    • @Pengyy : 请看一下并给我建议
    • @Rohit : 请看看这是我想要的方式
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签