动态更新矩阵的ng-repeat

时间:2015-09-03 17:26:57

标签: angularjs angularjs-ng-repeat ng-repeat page-refresh

我在模型中有矩阵(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。当用户更改大小矩阵时,它应该恢复为新大小的默认值。

my demo is here

1 个答案:

答案 0 :(得分:1)

在您的小提琴中,您的2D数组不是正确创建的。有关如何设置阵列的提示,请查看此SO question

我已经更改了代码的这些要点:

  • 使用ng-options获取长度和宽度下拉列表。这比ng-repeat更容易。
  • 从宽度和长度下拉列表中移除了点击事件,并为宽度和长度范围变量添加了$watch以更新地图。
  • 更新了2d数组的创建。

以下是您的代码的工作演示或此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>

相关问题