19

The following code makes the client.name an anchor on each client in clients. I am interested in having the entire <tr> element be that link however. ng-href does not work on the <tr> element.. what can I do so that the entire row is a single link instantiated by ng-href?

<tr ng-repeat="client in clients">
    <td><a ng-href="#/user/{{client.tagid}}">{{client.firstname}}</a></td>
    <td>{{client.lastname}}</td>
    <td>{{client.inumber}}</td>
</tr>

What I am looking to do is something like this.. which of course does not work..

<a ng-href="#/user/{{client.tagid}}">
    <tr ng-repeat="client in clients">
        <td>{{client.firstname}}</td>
        <td>{{client.lastname}}</td>
        <td>{{client.inumber}}</td>
    </tr>
</a>

OR

<tr ng-repeat="client in clients" ng-href="#/user/{{client.tagid}}">
    <td>{{client.firstname}}</td>
    <td>{{client.lastname}}</td>
    <td>{{client.inumber}}</td>
</tr>
2
  • 2
    Your last approach should work.
    – zs2020
    Aug 20, 2013 at 20:48
  • only for give another option for you. I used the following: <tr ng-repeat="client in clients" ui-sref="user({tagid: client.tagid})" > In your route config you may have a route like that: url: '/user/:tagid', so. this can work for you too. I hope this can help you in another time. Mar 8, 2016 at 13:21

9 Answers 9

32

You can use an ng-click (instead of onClick) as Jason suggests as well.

Something like:

HTML

<tr ng-repeat="client in clients" ng-click="showClient(client)">
    <td><a ng-href="#/user/{{client.tagid}}">{{client.firstname}}</a></td>
    <td>{{client.lastname}}</td>
    <td>{{client.inumber}}</td>
</tr>

Controller

$scope.showClient = function(client) {
  $location.path('#/user/' + client.tagid);
};

And styling to make it show as an clickable element (wont work in IE7)

CSS

tr {
  cursor: pointer;
}
// or
[ng-click] {
  cursor: pointer;
}
6
  • 3
    Angular.js has a special handler for this: docs.angularjs.org/api/ng.directive:ngClick Aug 20, 2013 at 20:47
  • ahh yes, I didn't even think to use it in this context. I'll update. Thanks! Aug 20, 2013 at 20:49
  • Updated answer using a controller function, ng-click may not like what I was trying to do. Aug 20, 2013 at 20:57
  • 2
    In the controller you should also use the $location service and $location.path('/user/' + client.tagid). This will let you use both html5 mode and hashbangs prefixed urls. Also if you really want to use window, try using the $window service which will give you flexibility for testing later on.
    – DerekR
    Aug 20, 2013 at 22:12
  • If you do not want to write the showClient function to every controller, you can use a directive like in the answer stackoverflow.com/a/23699554/1878731
    – mirelon
    May 16, 2014 at 15:51
11

I wrote a directive so that you can simply write:

<tr ng-repeat="client in clients" such-href="#/user/{{client.tagid}}">

The source:

app.directive('suchHref', ['$location', function ($location) {
  return{
    restrict: 'A',
    link: function (scope, element, attr) {
      element.attr('style', 'cursor:pointer');
      element.on('click', function(){
        $location.url(attr.suchHref)
        scope.$apply();
      });
    }
  }
}]);
2
  • 4
    Very useful. I used $location.path() instead because url() wouldn't work. Also, with $location.path(), the url must not include the leading # (it must start with /). Jul 15, 2014 at 14:02
  • If you really want it to be a standard link so that "Open in new tab" etc. would work, you can use this directive: stackoverflow.com/questions/18344569/… Jul 19, 2016 at 8:27
4

I use my own Angular directive that automatically wraps every cell in the row with a link.

The advantages are:

  • You don't duplicate code.
  • There is a regular link in every cell so things like "Open in new tab" (middle button or CTRL+click) works as expected (in opposite of the ng-click version).

HTML usage:

<tr row-href="#/user/{{client.tagid}}">
    <td>...</td>
    <td>...</td>
</tr>

Directive code (in TypeSript):

export class RowHrefDirective implements ng.IDirective {

    constructor(private $compile: ng.ICompileService) {
    }

    restrict = "A";

    scope = {
        rowHref: "@rowHref"
    };

    link = (scope: Scope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes): void => {
        const cells = element.children("td[skip-href!='yes'],th[skip-href!='yes']");

        cells.addClass("cell-link");

        for (const cell of cells.toArray()) {
            const link = jQuery(`<a ng-href="{{ rowHref }}"></a>`);
            this.$compile(link)(scope);
            jQuery(cell).prepend(link);
        }
    }
}

Required CSS code (to fill the whole cell with the link):

td.cell-link,
th.cell-link {
    position: relative;
}

td.cell-link a,
th.cell-link a {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
    }
}
2
  • This is awesome! Took me a while to adapt it to also work with ui-sref, but works great now. Thank you!!!
    – qqilihq
    Nov 5, 2016 at 20:25
  • @qqilihq Do you mind sharing your adapted solution for ui-sref?
    – sfs
    Aug 1, 2017 at 8:28
3

This is a CSS and HTML issue, not specific to AngularJS. The only allowed child of a <tr> is a <td>, and so you need to wrap the content of each cell in an anchor. You also need to make the anchor a block element to make it the full height/width of its container:

<tr ng-repeat="client in clients">
  <td>
    <a style="display: block;" ng-href="#/user/{{client.tagid}}">
      {{client.firstname}}
    </a>
  </td>
  <td>
    <a style="display: block;" ng-href="#/user/{{client.tagid}}">
      {{client.lastname}}
    </a>
  </td>
  <td>
    <a style="display: block;" ng-href="#/user/{{client.tagid}}">
      {{client.inumber}}
    </a>
  </td>
</tr>
1
<tr ng-repeat="client in clients" ng-href="#/user/{{client.tagid}}">
    <td>{{client.firstname}}</td>
    <td>{{client.lastname}}</td>
    <td>{{client.inumber}}</td>
</tr>

This is with the referrence to the options provided which may work. I think this binds the entire row with the each field in the row. but is not clickable. how to do that. i mean we should be able to click so that another view/module can be open.

1

As requested by @sfs, here’s the solution which we’re using for ui-sref (Angular 1.5; TypeScript code, apologies for any inconvenience).

Credits: The code is based on the awesome answer by Martin Volek:

import { IDirective, IDirectiveFactory, ICompileService, forEach, element } from 'angular';

export default class RowUiSrefDirective implements IDirective {

  restrict = 'A';
  scope = { rowUiSref: '@rowUiSref' };

  constructor(private $compile: ICompileService) { }

  link = (scope, elm, attrs) => {
    if (elm[0].tagName !== 'TR') {
      throw new Error('This directive should only be used in <tr> elements.');
    }

    forEach(elm.children(), (cell) => {

      if (cell.attributes['skip-href'] && cell.attributes['skip-href'].value !== 'false') {
        return;
      }

      cell.className += ' cell-link';
      let link = element('<a ui-sref="{{rowUiSref}}"></a>');
      this.$compile(link)(scope);
      element(cell).prepend(link);
    });
  };

  static factory(): IDirectiveFactory {
    let directive = ($compile: ICompileService) => new RowUiSrefDirective($compile);
    directive.$inject = ['$compile'];
    return directive;
  };

}

Directive initialization:

import { module } from 'angular';
import RowUiSrefDirective from './rowUiSref';

module('app').directive('rowUiSref', RowUiSrefDirective.factory());

Example usage:

<table>
  <tr ng-repeat="item in itemController.items"
      row-ui-sref="state.item({itemId: '{{item.id}}'})">
    <td>{{item.name}}</td>
    <td>{{item.label}}</td>
  </tr>
</table>
0

An ugly solution would be to just have 1 table cell which contains the link, then within that add another table with a table row and the other cells. So it would look like;

<tr ng-repeat="client in clients">
    <a ng-href="#/user/{{client.tagid}}">
        <table>
            <tr>
                <td>{{client.firstname}}</td>
                <td>{{client.lastname}}</td>
                <td>{{client.inumber}}</td>
            </tr>
        </table>
    </a>
</tr>

I do not agree with using tables for layout!

However, you are using JavaScript and angularjs, so you would be just as good adding a click event to the table row which sends the user to the url via window.location e.g.

<tr ng-repeat="client in clients" ng-click="ChangeLocation([yoururl])">    
    <td>{{client.firstname}}</td>
    <td>{{client.lastname}}</td>
    <td>{{client.inumber}}</td>    
</tr>

Then have a function within your $scope to handle this;

$scope.ChangeLocation = function(url){
    window.location = url;
}
0

Try for this...

HTML --->

<ul ng-repeat ="item in itemList "> <li><a data-ng-href="{{getUrl(item)}}">{{item.Name}}</a></li> </ul>

JS --->

$scope.getUrl = function (item) { return '/<give your path here>/' + item.ID; };

0

I adapted Martin Volek's Typescript code to make an AngularJS 1.x directive:

app.directive('rowHref', function ($compile)
{
  return {
    restrict: 'A',
    link: function (scope, element, attr)
    {
      scope.rowHref=attr.rowHref;
      var cells = element.children("td");
      angular.forEach(cells, function (cell)
      {
        $(cell).addClass("cell-link");
        var newElem = angular.element('<a ng-href="{{ rowHref }}"></a>');
        $compile(newElem)(scope);
        $(cell).append(newElem);
      });
    }
  }
});

Add his same HTML and CSS

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.