以角度js动态添加字段到JSON数组

时间:2014-09-24 12:06:09

标签: angularjs

我有两个JSON数组,一个用于标头,另一个用于数据。我正在处理标题,现在我正在使用ng-repeat显示数据。工作正常。但是,我想从视图中动态地将数据添加到$ scope.data。我已经在表格的最后一行创建了一个按钮作为'添加行'单击它,将为每列填充最后一行输入框。从这里开始,我没有找到继续进行的方法...因为我是角度js的新手。

请帮帮我。

HTML代码和JS粘贴在下面。

'use strict';

angular.module('mean.system').controller('IndexController', ['$scope', '$http', 'Global','$window',
  function($scope, $http,$window) {


    $scope.header = [{'field':'first_name', 'displayName':'First name','type':'required'},{'field':'last_name', 'displayName':'Last Name','type':'required'},{'field':'email','displayName':'Email Address','type':'required'}];
    $scope.headerAll=[{'field':'first_name', 'displayName':'First name','type':'required'},{'field':'last_name', 'displayName':'Last Name','type':'required'},{'field':'email', 'displayName':'Email','type':'required'},{'field':'isMarried', 'displayName':'marital Status','type':'optional'},{'field':'nick_name', 'displayName':'Nick Name','type':'optional'}]
    $scope.optional = [];
    $scope.data=[{'first_name':'ruth','last_name':'vick','email':'ruthvick@gmail.com','isMarried':'no','nick_name':'ruthu'},{'first_name':'rahul','last_name':'kumar','email':'rahul@gmail.com','isMarried':'no','nick_name':'rahul'},{'first_name':'vicky','last_name':'gupta','email':'vicky@gmail.com','isMarried':'no','nick_name':'vicky'}]
    $scope.headerAll.forEach(function(result){
        if (result.type === 'optional') {
          $scope.optional.push(result);
        }
    });
    console.log($scope.optional);
    $scope.addColumn = function(field){
      /*$scope.toPush = {'field':'marital', 'displayName':'married','type':'required'};
      $scope.header.push($scope.toPush);*/
      $scope.optional.forEach(function(result){
        if (result.field === field) {
          $scope.header.push(result);
        }
      });

    };
    $scope. deleteColumn = function(field,index){
        console.log(index);
        $scope.optional.forEach(function(result){
          console.log(result.field);
        if (result.field === field) {
           $scope.header.splice(index,1);
        }

      });

    };
    $scope.toPoint = function(index){
      $scope.index = index;
      console.log($scope.index);

    };
    $scope. editColumn = function(currentField,fieldToEdit,index){

      $scope.header.splice($scope.index,1);
      $scope.headerAll.forEach(function(result){
        if(result.field === fieldToEdit){
          $scope.header.splice($scope.index,0,result);
        }

      });      
    };
    $scope.showAddBtn = 'true';
    $scope.addRowButton = function(){
      $scope.showInput = 'true';
      $scope.showAddBtn = 'false';
    };
    $scope.cancel = function(){
      $scope.showInput = 'false';
      $scope.showAddBtn = 'true';
    };
    $scope.addRow = function(){
      $scope.headerAll.forEach(function(result){
        var x= result.field;
        console.log(x);
        $scope.rowObj = {
              x : x
        };
        console.log($scope.rowObj);                  
      });    
    };
  }
]);


<div>   
    <table class="table table-bordered table-hover">
        <thead class="wrapper">
            <tr>
                <th ng-repeat="data in header">
                    <div class="col-md-9">{{data.displayName}}</div>
                    <div class="col-md-1">
                        <button href=""   ng-click="deleteColumn(data.field,$index)"><span class=" glyphicon glyphicon-trash pull-right"> </span></button>
                    </div>
                    <div class="dropdown col-md-1" >
                      <button class="glyphicon glyphicon-pencil dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" ng-click = "toPoint($index);">
                        <span class="caret"></span>
                      </button>
                      <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1" ng-repeat="optionalHeader in optional">
                        <li role="presentation" ng-repeat="dataEdit in headerAll"><a role="menuitem" tabindex="-1" href="" ng-click="editColumn(data.field,dataEdit.field,$index)">{{dataEdit.displayName}}</a></li>
                      </ul>
                    </div>
                </th>
                <th><div class="dropdown" >
                      <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown">
                        Add Columns
                        <span class="caret"></span>
                      </button>
                      <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1" ng-repeat="optionalHeader in optional">
                        <li role="presentation" ng-repeat="optionalHeader in optional"><a role="menuitem" tabindex="-1" href="" ng-click="addColumn(optionalHeader.field)">{{optionalHeader.displayName}}</a></li>
                      </ul>
                    </div>
                </th>

            </tr>
        </thead>

      <tbody >
        <tr class="active" ng-repeat="row in data">
            <td ng-repeat="fields in headerAll">
              {{row.fields.field}}
            </td>
        </tr>
        <tr>
                <td ng-repeat="fields in header">
                    <input type="text" ng-show="showInput" ng-model="input"></input>
                </td>
                <td>
                    <a href="" style="color:#63822E" ng-click="addRow()">
                        <h5 ng-show= "showInput"><span class="glyphicon glyphicon-ok"  ></span></h5>

                    </a>
                    <a href="" style="color:#63822E">
                        <h5 ng-show= "showInput" ng-click="cancel()"><span class="glyphicon glyphicon-remove" ></span></h5>
                    </a>
                    <a href= "" style="color:#63822E" ng-click = "addRowButton()" ng-show = 'showAddBtn'>
                        <h5 ><span class="glyphicon glyphicon-plus-sign"></span>
                                Add a new row 
                        </h5>
                    </a>
                </td>
            </tr>
    </tbody> 
    </table>
</div>

我希望输入框中输入的内容在$ scope.data中被推送,其中相应的标题取自$ scope.headerAll;

感谢。

1 个答案:

答案 0 :(得分:2)

Here是一个示例,其中<input>字段的每次更新都会直接更新数据数组中的新对象。保存按钮仅隐藏<input&gt;领域。我认为更好的方法是在保存功能中验证数据,并在数据正确时仅推送它。因此,我没有删除以下行

//$scope.newObject = {};

//Maybe some validation
//$scope.data.push($scope.newObject);

<强> HTML

<div ng-app ng-controller="Controller">
    <table>
       <tr>
           <th ng-repeat="header in headers">{{header.name}}</th>
        </tr>
        <tr ng-repeat="row in data">
            <td>{{row.firstname}}</td>
            <td>{{row.lastname}}</td>
            <td>{{row.gender}}</td>
        </tr>
        <tr ng-show="creatingObject">
            <td ng-repeat="header in headers">
                <input type="text" ng-model="newObject[header.field]">
            </td>
        </tr>
        <tr>
            <td></td>
            <td><button ng-show="creatingObject" ng-click="saveRow()">Save</button></td>
            <td><button ng-hide="creatingObject" ng-click="addRow()">Add Row</button></td>
        </tr>

    </table>
</div>

<强>控制器

function Controller($scope) {
    $scope.headers = [{ 'field': 'firstname', 'name': 'Firstname' }, 
                      { 'field': 'lastname', 'name': 'Lastname' }, 
                      { 'field': 'gender', 'name': 'Gender' }];

    $scope.creatingObject = false;

    $scope.data = [{'firstname': 'john', 'lastname': 'Doe', 'gender': 'male'} ];

    $scope.addRow = function() {
        //$scope.newObject = {};
        var length = $scope.data.push({});
        $scope.newObject = $scope.data[length - 1] ;
        $scope.creatingObject = true;
    }

    $scope.saveRow = function() {
        //Maybe some validation
        //$scope.data.push($scope.newObject);
        $scope.creatingObject = false;
    }
}

希望有所帮助。