我在模型中有矩阵(2D数组)cells
,我在表格中表示。
<tr ng-repeat='row in cells track by $index'>
<td ng-repeat='cell in row track by $index'>
{{cell}}
</td>
</tr>
我想添加一个下拉按钮来调整长度和宽度,
<select ng-model="length" >
<option ng-repeat="size in sizes" ng-click="setLength(size)">{{size}} </option>
</select>
但无法刷新ng-repeat
。对于刷新页面,我在$scope.$apply()
cells
$scope.cells = new Array($scope.width);
for (var i = 0; i < $scope.cells.length; i++) {
$scope.cells[i] = new Array($scope.length);
for (var j = 0; j < $scope.length; j++) {
$scope.cells[i][j] = 'cell';
}
}
$scope.$apply();
但它没有帮助。如何刷新ng-repeat
?
P.S。当用户更改大小矩阵时,它应该恢复为新大小的默认值。
答案 0 :(得分:1)
在您的小提琴中,您的2D数组不是正确创建的。有关如何设置阵列的提示,请查看此SO question。
我已经更改了代码的这些要点:
ng-options
获取长度和宽度下拉列表。这比ng-repeat
更容易。$watch
以更新地图。以下是您的代码的工作演示或此fiddle。
var myapp = angular.module('mapApp', []);
myapp.controller('editorController', function ($scope) {
$scope.cells = [
[]
];
$scope.sizes = [];
makeSizes();
$scope.length = $scope.sizes[0];
$scope.width = $scope.sizes[0];
$scope.$watch('[width,length]', makeMap, true);
function makeMap() {
var cols = $scope.width,
rows = $scope.length;
console.log('makeMap');
$scope.cells = matrix(rows, cols, 'cell');
}
function matrix(rows, cols, defaultValue) {
// code from here https://stackoverflow.com/questions/966225/how-can-i-create-a-two-dimensional-array-in-javascript
var arr = [[]];
// Creates all lines:
for (var i = 0; i < rows; i++) {
// Creates an empty line
arr[i] = [];
// Adds cols to the empty line:
arr[i] = new Array(cols);
for (var j = 0; j < cols; j++) {
// Initializes:
arr[i][j] = defaultValue;
}
}
return arr;
}
makeMap();
function makeSizes() {
for (var i = 0; i < 5; i++) {
$scope.sizes.push(i + 3);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="mapApp" ng-controller="editorController">
<label>Length</label>
<select ng-model="length" ng-options="length for length in sizes">
</select>
<table>
<label>Width</label>
<select ng-model="width" ng-options="width for width in sizes">
</select>
<table>
<tbody>
<tr ng-repeat="row in cells track by $index">
<td ng-repeat="cell in row track by $index">
{{cell}}
</td>
</tr>
</tbody>
</table>
</div>