bryan60 bryan60 - 2 months ago 15
AngularJS Question

Trouble using pseudo selector with a directive inside ng-repeat

I have a directive for a table with collapsible rows that only allows one row to be open at a time like this:

HTML:

<div class="my-table">
<div class="table-header">
... table headers ...
</div>
<my-table-row ng-repeat="itm in itms" itm="itm"></my-table-row>
</div>


JS Directive:

app.directive('myTable', function() {
return {
restrict: 'E',
scope: {
itms: '='
},
controller: 'TableController',
templateUrl: '/views/directives/my-table.html'
};
});


JS Controller:

app.controller('TableController', ['$scope', function($scope) {
$scope.rows = [];

$scope.toggleRow = function(row) {
row.open = !row.open;
};

this.addRow = function addRow(row) {
$scope.rows.push(row);
};

this.toggleOpen = function toggleOpen(selectedRow) {
angular.forEach($scope.rows, function(row) {
if (row === selectedRow) {
$scope.toggleRow(selectedRow);
} else {
row.open = false;
}
});
};
}]);


and the rows like this:

HTML:

<div class="table-row" ng-class="{ 'open': open }" ng-click="toggleOpen(this)">
... row contents code ...
</div>


JS Directive:

app.directive('myTableRow', function() {
return {
require: '^myTable',
restrict: 'E',
scope: {
itm: '='
},
link: function(scope, element, attrs, tableCtrl) {
scope.open = false;
scope.toggleOpen = tableCtrl.toggleOpen;
tableCtrl.addRow(scope);
},
templateUrl: '/views/directives/my-table-row.html'
};
});


used in template like this:

<my-table itms="itms"></my-table>


This all works, but I have a CSS pseudo element to round the corners of the final row like:

.table .table-row:last-child {
border-radius: 0 0 4px 4px;
}


However, ng-repeat is wrapping a tag around my table rows which is causing the pseudo selector to see them all as the last child. I've tried restructuring, tried using $last and making an actual class for the last row, moving things around, but I'm out of ideas. Any thoughts out there?

Answer

as I understood, css class table-row is located within myTableRow directive, which does not have replace: true property. This means that table-row css class is wrapped by my-table-row directive attribute, so, in order to get to the last row, your CSS rule should be:

.table my-table-row:last-child .table-row {
  border-radius: 0 0 4px 4px;
}
Comments