【问题标题】:create a dynamic json matrix by using angularjs使用 angularjs 创建动态 json 矩阵
【发布时间】:2015-12-29 23:38:27
【问题描述】:

我是 Angularjs 的新手,这是我在论坛上的第一篇文章,但我尝试了很长时间使用 angularjs 创建动态矩阵。经过一些研究,我不确定使用 Angularjs 是否真的可以实现我想要做的事情。让我给你看一张可以解释我期望的图片:

例如,对于这张图片,我想创建这个 JSON 对象:

{
  "row1": {
      "column1": 0,
      "column2": 1,
      "column3": 2
   }
   "row2": {
      "column1": 2,
      "column2": 0,
      "column3": 3
   }}

当然,我们可以添加一个新列或一个具有不同名称的新行,这就是为什么它是动态的。目前我在代码方面有这个:

HTML

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
	src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="js/addMatrix.js"></script>
</head>
<body>
	<div ng-app="App" ng-controller="MainCtrl">
		<p>Add a new element :</p>
		<table>
			<tr>
				<td data-ng-repeat="data in texts">
					<button>{{data.text}}</button>
				</td>
				<td data-ng-repeat="field in fields">
					<form ng-submit="submit(text)">
						<input type="text" ng-model="text" name="text"
							placeholder="New Category" />
					</form>
				</td>
				<td>
					<button ng-click="addNewChoice()">+</button>
				</td>
			</tr>
		</table>
		<div ng-if="texts.length > 0 && hasMatrix">
			<table>
				<tr>
					<td>
						<p></p>
					</td>
					<td data-ng-repeat="column in columns">{{column.id}}</td>
				</tr>
				<tr data-ng-repeat="row in rows">
					<td>{{row.id}}</td>
					<td data-ng-repeat="column in columns">
							<select name="singleSelect">
								<option>0</option>
								<option>1</option>
								<option>2</option>
								<option>3</option>
							</select>
					</td>
				</tr>
			</table>
			<br/>
			<button ng-click="addColumn()">Add a column</button>
			<button ng-click="addRow()">Add a row</button>
			<button>Validate</button>
			<br /> <br />
			<form ng-submit="process(data)" ng-if="hasClicked">
				name : <input type="text" ng-model="data" name="data"
					placeholder="name" />
			</form>
		</div>
		<div ng-if="texts.length > 0 && !hasMatrix">
			<button ng-click="create()">Create a new Matrix</button>
		</div>
		<div ng-if="firstRowColumn">
			<form>
				First row's name : <input type="text" ng-model="matrix.row"
					name="row" placeholder="New Category" /><br /> First Column's name
				: <input type="text" ng-model="matrix.column" name="column"
					placeholder="New Category" /><br /> <input type="submit"
					ng-click="createFirst(matrix)" value="generate" />
			</form>
		</div>
	</div>
</body>
</html>

Angularjs

var myApp = angular.module('App', []);

myApp.controller('MainCtrl',function ($scope) {
	$scope.fields=[];
	$scope.texts=[];
	$scope.hasMatrix = false;
	$scope.hasClicked = false;
	$scope.firstRowColumn = false;
	$scope.hasNewRow = false;
	$scope.hasNewColumn = false;
	$scope.rows=[];
	$scope.columns=[];
	$scope.test = {
		    singleSelect: null,
    };
	$scope.addNewChoice = function() {
		var newItem = $scope.fields.length + 1;
		if (newItem < 2) {
			$scope.fields.push({'id' : 'field' + newItem});
		}
	};
	$scope.process = function(data) {
		if ($scope.hasNewRow) {
		   $scope.rows.push({'id' : data});
		}
		if ($scope.hasNewColumn) {
			$scope.columns.push({'id' : data});
		}
		$scope.hasNewColumn = false;
		$scope.hasNewRow = false;
		$scope.hasClicked = false;
	};
	
	$scope.addRow = function() {
		$scope.hasClicked = true;
		$scope.hasNewRow = true;

	};
	$scope.addColumn = function() {
		$scope.hasClicked = true;
		$scope.hasNewColumn = true;

	};	
	$scope.create = function(field) {
		$scope.input = field;
	};
	
	$scope.submit = function(text) {
	    var lastItem = $scope.fields.length - 1;
	    $scope.fields.splice(lastItem);
        $scope.texts.push({'text' : text});    
	};
	$scope.create = function() {
		$scope.firstRowColumn = true;
	};
	$scope.createFirst = function(matrix) {
		$scope.firstRowColumn = false;
		$scope.hasMatrix = true;
		$scope.rows.push({'id' : matrix.row});
		$scope.columns.push({'id' : matrix.column});
	}
});

如果有人可以帮助我,那就太好了。谢谢

【问题讨论】:

  • 为什么不对 UI 的每一行和每一列使用 ng-repeat 并且每次单击新行或新列时,您只需附加一个新元素(如果是行,则为数组,如果是数字每行的列数)?
  • 为了确保我理解您的解决方案,您能否在我的照片上给我这个方法的结果?它将是 [{0,1,2},{2,0,3}],对吗?如果我是对的,我忘了提到行和列的名称非常重要,因为这个 Web 应用程序将是一个 Web 服务,而我尝试创建的 json 对象将是这个 Web 服务的结果
  • 我的意思是 [[0,1,2],[3,4,5]] 实际上。您可以稍后通过迭代矩阵来提取每一行的名称(matrix.length 是行数,matrix[0].length 是列数)。将它连接到一个字符串相当容易。

标签: javascript angularjs json


【解决方案1】:

你可以,而且它非常适合角度模型。我在下面实现了一个非常简单的版本,它将矩阵表示为数字数组的数组,并使用第一行(必须始终存在)来确定列数;您可以将其扩展为更适合您的用例的内容。

下面的代码有两个陷阱:

  • 单元格的ng-model 使用row[$index],而不是看似等效的cell
  • 列的ng-repeat 使用track by $index

对于ng-model="row[$index]",这是由于 Angular 中 2 路绑定的工作方式:您必须引用一个对象(行数组)而不是原语,以便它可以检测更新。详情请见this SO

对于ng-repeat="... track by $index",这是为了避免“欺骗”错误。 ng-repeat 需要一种方法来跟踪正在迭代的集合的独特元素;如果你在迭代一个对象的集合,Angular 知道该怎么做(注意我在迭代行时不需要这样做,因为每一行都是一个数组,这是 JS 中的一种对象);否则,您需要告诉它是什么使每个元素独一无二(在这种情况下,它在集合中的位置,由$index 提供)。您可以在this Angular docs page找到更多详细信息。

angular.module('App', [])
.controller('MainCtrl', ['$scope', function($scope) {
  $scope.matrix = [[0]];
  
  $scope.addColumn = function() {
    $scope.matrix.forEach(function(row) {
      row.push(0);
    });
  };
  
  $scope.addRow = function() {
    var columnCount = $scope.matrix[0].length;
    var newRow = [];
    for (var i = 0; i < columnCount; i++) {
      newRow.push(0);
    }
    $scope.matrix.push(newRow);
  };

  $scope.deleteRow = function(idx) {
    if (idx >= 0 && idx < $scope.matrix.length) {
      $scope.matrix.splice(idx, 1);
    }
  };
  
  $scope.deleteColumn = function(idx) {
    if (idx >= 0 && idx < $scope.matrix[0].length) {
      $scope.matrix.forEach(function(row) {
        row.splice(idx, 1);
      });
    }
  };

}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
<div ng-app="App" ng-controller="MainCtrl">
  <table>
    <tbody>
      <tr>
        <th></th>
        <th ng-repeat="column in matrix[0] track by $index">
          <button ng-disabled="matrix[0].length <= 1"
                  ng-click="deleteColumn($index)">
            Delete
          </button>
        </th>
      </tr>
      <tr ng-repeat="row in matrix">
        <th>
          <button ng-disabled="matrix.length <= 1"
                  ng-click="deleteRow($index)">
            Delete
          </button>
        </th>
        <td ng-repeat="cell in row track by $index">
          <input type="number" ng-model="row[$index]">
        </td>
      </tr>
    </tbody>
  </table>
  <button type="button" ng-click="addRow()">Add Row</button>
  <button type="button" ng-click="addColumn()">Add Column</button>
  <h3>As JSON:</h3>
  <pre><code>{{matrix | json}}</code></pre>
</div>

【讨论】:

  • 非常感谢,这正是我想要的!
【解决方案2】:

Angularjs:使用数据条目表创建动态 JSON obj 数组。
步骤:展示了几个输入类型示例。

  1. 使用默认字段初始化 JSON 对象并推入数组 obj。
  2. 在数组 obj 上使用 ng-repeat 使用 track by $index。
  3. 从控制器初始化模型并使用 ng-model。
  4. 使用 ng-init from view 来初始化模型,以使用自动填充的数据进行输入。

var app = angular.module("myApp", []);
app.controller('myCtrl', function($scope) {
  $scope.vendorTypeEnums = [
    'main',
    'sub'
  ];
  $scope.brand ="brandX";
  $scope.vendorDataList = [];
  $scope.initVendorList = function(vendorsCount) {
  $scope.vendorDataList = [];
    for (var i = 0; i < vendorsCount; i++) {
      $scope.createVendorObj();
    }
    console.log($scope.vendorDataList);
  }

  $scope.createVendorObj = function() {
    var row = {
      vendorName: '',
      brand: $scope.brand,
      vendorType: '',
      layerLevel: 0,
    };
    $scope.vendorDataList.push(row);
  };
  $scope.addVendorData = function() {
    console.log($scope.vendorDataList);
    alert(JSON.stringify($scope.vendorDataList));
  };

});
<html>

<head>
  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">

  <!-- Optional JavaScript -->
  <!-- jQuery first, then Popper.js, then Bootstrap JS -->
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>

  <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>

  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.7.0/angular.js"></script>
</head>

<body ng-app="myApp" ng-controller="myCtrl">
  <!--HTML Piece of code -->
  <div class="form-group row">
    <label for="city" class="col-sm-4 col-form-label">Choose
								Vendors Count:</label>
    <div class="col-sm-4">
      <input type="number" class="form-control" ng-model="vendorsCount" ng-change="initVendorList(vendorsCount)">
    </div>
  </div>

  <div>
    <table class="table table-sm">
      <thead>
        <tr>
          <th scope="col">Vendor Name</th>
          <th scope="col">Vendor Type</th>
          <th scope="col">Layer Level</th>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="row in vendorDataList track by $index">
          <!--Vendor name column -->
          <td><input type="text" class="form-control" id="vendorName" data-ng-model="row.vendorName"></td>
          <!--Vendor type column-->
          <td>
            <select class="form-control " id="" ng-model="row.vendorType">
              <option title="NA"></option>
              <option ng-repeat="vendorType in vendorTypeEnums" title="{{vendorType}}" value="{{vendorType}}">{{vendorType}}</option>
            </select>
          </td>
          <!--Layer Level column-->
          <td><input type="number" class="form-control" ng-model="row.layerLevel" ng-init="row.layerLevel=$index+1" ng-value="$index+1"></td>
          <!-- Remove this row -->
          <td><input type="button" class="form-control" value="Remove[-]" ng-click="vendorDataList.splice($index,1)"></td>
        </tr>
      </tbody>
    </table>
  </div>
  <div class="d-flex justify-content-end ">
    <input type="button" class="form-control col-3 btn-secondary btn-sm" value="Add[+]" ng-click="createVendorObj()">
  </div>
  <div class="d-flex justify-content-center ">
    <input type="button" class="form-control col-3 btn-primary" value="Show" ng-click="addVendorData()">
  </div>

</body>

</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-07
    • 1970-01-01
    • 2015-11-24
    • 1970-01-01
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多