Issue
I'm using AngularJS and have table rows where I want the entire row to be clickable, but I also have a clickable link in the last column. Something like this:
<tr x-ng-click="goSomehere()">
<td>text</td>
<td>text</td>
<td>text</td>
<td>text</td>
<td>text</td>
<td>text</td>
<td>
<a href="" x-ng-click="openEditor()">
edit
</a>
</td>
</tr>
Now I really wish that I don't have to repeat the x-ng-click="goSomewhere()" in all TD elements (since it's over 30), but I also want the link in the last column to open the editor. Is there an easy way to excluce the last column from the x-ng-click attribute given in the TR element?
Solution
Yes, there is a way to achieve that without repeating the x-ng-click
directive in each element. You can use event delegation in AngularJS to handle the click event on the entire row and then conditionally execute different actions based on the clicked element.
Here's an example of how you can implement it:
Add a single click event handler to the
<tr>
element:In your controller or directive, define the
handleRowClick
function: javascript
In the handleRowClick
function, we check if the clicked element is an <a>
tag. If it is, we don't execute the row click action (goSomewhere()
). Instead, we let the openEditor()
function handle the link click action. We also use event.stopPropagation()
in the openEditor
function to prevent the row click event from bubbling up and triggering the row click action.
With this approach, you only need to define the click event once on the <tr>
element, and it will handle both row clicks and link clicks within the row.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.handleRowClick = function(event) {
var target = event.target;
var isLinkClicked = target.tagName.toLowerCase() === 'a';
if (!isLinkClicked) {
$scope.goSomewhere();
}
};
$scope.goSomewhere = function() {
alert('Row clicked');
};
$scope.openEditor = function(event) {
event.stopPropagation();
alert('Edit link clicked');
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<table>
<tr ng-app="myApp" ng-controller="myCtrl" ng-click="handleRowClick($event)">
<td>Row 1</td>
<td>Row 1</td>
<td>Row 1</td>
<td>Row 1</td>
<td>Row 1</td>
<td>Row 1</td>
<td><a href="" ng-click="openEditor($event)">edit</a></td>
</tr>
</table>
Answered By - Angie Florez
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.