Ajv2324
Ajv2324

Reputation: 522

How to change the property of a 2D array in AngularJS?

So I've got a dynamic table that I need to keep track of several properties of. I'm using angularJS to do this and a 2D array of objects to track the elements of the table.

My code looks like this:

$scope.table = [];
$scope.generateTable = function(){
    var table = [[], []];
    for (var i = 0; i < $scope.height; i++) {
        $scope.table[i] = []
        for (var j = 0; j < $scope.width; j++) {
            $scope.table[i].push({
                display: 'X',
                alive: false
            });
        }
    }
}

$scope.changeProp = function(x, y){
    $scope.table[x][y].alive = !$scope.table[x][y].alive;
    $scope.table[x][y].alive ? $scope.table[x][y].display = 'O' : $scope.table[x][y].display = 'X';
}

But it says 'cannot read property of undefined' whenever I try to run the changeProp() function. The elements exist in the array as they should and display properly on the front end, why can't I change the elements in the function with the syntax arr[][]?

EDIT: Upon further review, it appears the problem lies with width not being passed to changeProp properly. Here is the front end code:

<tr ng-repeat="x in table">
    <td ng-repeat="y in x track by $index" align="center" ng-click="changeProp($parent.index, $index)">
        {{ y.display }}
    </td>
</tr>

Upvotes: 0

Views: 41

Answers (3)

Jeet
Jeet

Reputation: 80

Pleas try as like below:

$scope.table = [{},{}];
$scope.generateTable = function(){
    var table = [{}, {}];
    for (var i = 0; i < $scope.height; i++) {
        $scope.table[i] = {};
        for (var j = 0; j < $scope.width; j++) {
            $scope.table[i].push({
                display: 'X',
                alive: false
            });
        }
    }
}

$scope.changeProp = function(x, y){
    x =parseInt(x);
    y= parseInt(y);
    $scope.table[x][y]['alive'] = !$scope.table[x][y]['alive'];
    $scope.table[x][y]['alive'] ? $scope.table[x][y]['display'] = 'O' : $scope.table[x][y]['display'] = 'X';
}

IN UI:

<tr ng-repeat="x in table">
    <td ng-repeat="y in x track by $index" align="center" ng-click="changeProp($index==0 ? 0 :$index--, $index)">
        {{ y.display }}
    </td>
</tr>

Upvotes: 1

Prateek Gupta
Prateek Gupta

Reputation: 1169

You have passed parent index in wrong way.

Edit $parent.index to $parent.$index.

<tr ng-repeat="x in table">
    <td ng-repeat="y in x track by $index" align="center" ng-click="changeProp($parent.$index, $index)">
        {{ y.display }}
    </td>
</tr>

Upvotes: 1

Ajv2324
Ajv2324

Reputation: 522

I've solved the problem.

I needed to init a variable to the index of the ng-repeat.

Example:

<tr ng-repeat="x in table" ng-init="outer = $index">
      <td ng-repeat="y in x track by $index" ng-init="inner = $index" align="center" ng-click="changeProp(outer, inner)">
              {{ y.display }}
      </td>
</tr>

Upvotes: 0

Related Questions