使用angularjs创建动态json矩阵

时间:2015-12-29 23:38:28

标签: javascript angularjs json

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

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

2 个答案:

答案 0 :(得分:3)

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

下面的代码有2个问题:

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

对于ng-model="row[$index]",这是由于Angular中的双向绑定如何工作:您必须引用一个对象(行数组)而不是一个基元,以便它可以检测更新。您可以在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>

答案 1 :(得分:0)

Angularjs:使用数据条目表创建动态JSON obj数组。
步骤:显示一些输入类型示例。

  1. 使用默认字段初始化JSON对象,然后将其放入数组obj。
  2. 使用$ index跟踪对数组obj使用ng-repeat。
  3. 从控制器初始化模型并使用ng-model。
  4. 从视图中使用ng-init初始化具有自动填充数据的输入的模型。

$uploadArtwork = $_FILES['asset_name']['tmp_name'];

if($uploadArtwork == null) {
$sql = "";
}

else {
$sql = ""; 
}
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));
  };

});