Angular Tip: ng-grid columns with actions

--

It’s pretty easy to create an ng-grid implementation that has selectable rows. I had to play around a bit to get the same type of grid to include a column with link buttons that execute a different action, however.

The steps to set up a grid with rows that when selected, execute an action was pretty straightforward. For example, the HTML <div> below uses a gridStyle class for formatting; shows the grid if the length of the list data field is > 0; uses the $scope variable listOfStuff to get at the list data; and on clicking a row ng-click calls to a function to act on the row using the selectedItem $scope variable.

<div class="gridStyle" ng-hide="list.length== 0" ng-grid="gridListOfStuff" ng-click="selectGridRow()"></div>

The function, selectGridRow() builds a Url to navigate to with the selected item id:

$scope.selectGridRow = function () { if ($scope.selectedItem[0].total != 0) { $location.path('items/' + $scope.selecteditem[0].id); }};

To add a column that included link buttons with a different action, I played around and found this solution. First, I added a column that did not specify a field, instead included a cellTemplate. I wrapped that HTML inside a <div> that used class grid-action-cell and the href links were wrapped in there. I used $event.stopPropagation() to prevent the ng-click action from acting like a selected row, and then call the delete function to handle the action. That delete function could as easily but a function that redirected to a new location in the app, as well.

The result is that I can select each row and navigate to the selected item page; but I can select the Delete link and stay on this page but execute the delete function to remove the row and refresh this page. Hope this helps someone in a similar situation. Cheers!

$scope.gridListOfStuff = { data: 'list', multiSelect: false, columnDefs: [{ field: 'name', displayName: 'Name'}, { field: 'description', displayName: 'Description'}, { displayName: 'Actions', cellTemplate: '<div class="grid-action-cell">'+ '<a ng-click="$event.stopPropagation(); deleteThisRow(row.entity);" href="#">Delete</a></div>'} ] };

Originally published July 20, 2014.

--

--

Cofounder / CIO Solliance; Cloud / Security Architect; Microsoft Regional Director and Azure MVP; author Learning WCF, Developing Microsoft Azure Solutions