Tale:
I've developed an array ($scope.mainArray
) that will be displayed in a <table>
with <tr>
elements using ng-repeat
as shown below:
+---+
| 1 |
+---+
| 2 |
+---+
| 3 |
+---+
Each object contains an array which is presented within <td>
tags using ng-repeat
like so:
+---+-----+-----+-----+
| 1 | 1-1 | 1-2 | 1-3 |
+---+-----+-----+-----+
| 2 | 2-1 | 2-2 | 2-3 |
+---+-----+-----+-----+
| 3 | 3-1 | 3-2 | 3-3 |
+---+-----+-----+-----+
Each <td>
represents a boolean variable. If it's true
, the background color of the <td>
turns green; otherwise, it remains default.
Challenge:
Whenever I set one boolean
to true
, all corresponding <td>
's in that column turn green. The code
$scope.mainArray[0].subArray[0].isGreen = true;
, intended to turn cell 1-1
green, ends up turning both 2-1
and 3-1
green as well.SSCCE:
Plunker: https://plnkr.co/edit/9q3PMO?p=preview
SO Snippet:
angular.module("App", [])
.controller("Controller", function($scope) {
var initSubArray = function() {
var data = [{
"value": 1,
"label": 1,
"isGreen": false
}, {
"value": 2,
"label": 2,
"isGreen": false
}, {
"value": 3,
"label": 3,
"isGreen": false
}];
return data;
};
var initMainArray = function() {
var data = [{
"value": 1,
"label": 1
}, {
"value": 2,
"label": 2
}, {
"value": 3,
"label": 3
}];
return data;
};
var putSubArray = function() {
var subArray = initSubArray();
for (i = 0; i < $scope.mainArray.length; i++) {
$scope.mainArray[i].subArray = subArray;
}
};
$scope.init = function() {
$scope.mainArray = initMainArray();
putSubArray();
$scope.mainArray[0].subArray[0].isGreen = true;
};
});
table {
border-collapse: collapse;
}
td {
border: solid;
}
.green {
background-color: #00FF00;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>
</head>
<body ng-app="App" ng-controller="Controller" ng-init="init()">
<table>
<tr ng-repeat="foo in mainArray">
<td>
{{foo.label}}
</td>
<td ng-repeat="bar in foo.subArray" ng-class="{'green' : bar.isGreen}">
{{foo.label}}-{{bar.label}}
</td>
</tr>
</table>
</body>
</html>