Reputation: 8413
Problem:
I have a table and a clickable <td>
. What I want to happen is when I clicked on any of the following <td>
It will become active but I can't do it right.
DOM
<table class="table-position">
<tr ng-repeat="i in [1,2,3]">
<td ng-repeat="j in [1,2,3]" ng-click="selectPosition(j)"
ng-class="{active: selectedPosition == j}"></td>
</tr>
</table>
Directive
$scope.selectPosition = function(position){
$scope.selectedPosition = position;
}
Text Render
i1-[j1,j2,j3]
i2-[j1,j2,j3]
i3-[j1,j2,j3]
Current Output: This is the current output when I'm clicking on any of the ff: <td>
[i1,j1],[i2,j1],[i3,j1]
Expected Output:
This is the expected output when I clicked on the center <td>
[i2,j2]
I already tried to pass array and object on the selectPosition
function but still not working. Not sure If I'm doing it right.
Please let me know if something is not clear. Thank you in advance.
Upvotes: 0
Views: 4930
Reputation: 2241
<table class="table-position" ng-controller="myCtrl">
<tr ng-repeat="i in [1,2,3]">
<td ng-repeat="j in [1,2,3]" ng-click="selectPosition($parent.$index, $index)"
ng-class="{active: (selectedPosition.parent == $parent.$index && selectedPosition.index == $index )}">{{ j }}</td>
</tr>
</table>
Pass $index and $parent.$index when td is clicked.
var app = angular.module("app", []);
app.controller("myCtrl", function ($scope) {
$scope.selectPosition = function ($parentIndex, $index) {
$scope.selectedPosition = {
parent: $parentIndex,
index: $index
};
}
})
Upvotes: 2
Reputation: 302
I'm sure you can make this prettier but the idea is that in your old code, the $scope.selectedPosition is always the same on each iteration of i, so naturally that j in each row gets active.
$scope.selectPosition = function(i, j){
$scope.selectedPosition = {};
$scope.selectedPosition.i = i;
$scope.selectedPosition.j = j;
}
<table class="table-position">
<tr ng-repeat="i in [1,2,3]">
<td ng-repeat="j in [1,2,3]" ng-click="selectPosition(j)"
ng-class="{active: (selectedPosition.j == j && selectedPosition.i == i)}"></td>
</tr>
</table>
Upvotes: 0