clementescolano
clementescolano

Reputation: 505

How to add links in all cells of a table in Angular?

I have currently a table made with ng-repeat in Angular. The cells value is set by some variable in scope.

<tbody>
  <tr ng-repeat="item in items" myDirective>
    <td>{{item.title}}</td>
    <td>{{item.field}}</td>
  </tr>
</tbody>

What I would like to do is to have this in the end :

<tbody>
  <tr ng-repeat="item in items" myDirective>
    <td><a href="{{item.link}}">{{item.title}}</a></td>
    <td><a href="{{item.link}}">{{item.field}}</a></td>
  </tr>
</tbody>

So I created a directive in order to do that but I don't go anywhere with it. I tried to get every child of the tr element, then surround the html of the (td) childs by a tag but it seems that the binding removes the tag and replace it with vanilla item title and field.

Here is my code so far, which is setting the a tag with a status website on the first td tag (title) but can't make it work.

angular.module('myApp')
  .directive('myDirective', function () {
    return {
      restrict: 'A',
      link: function postLink(scope, element, attrs) {
        var cellules = element.children(); // get td elements
        angular.element(cellules[0]).html($compile('<a href="http://website">' + angular.element(cellules[0]).html() + '</a>')(scope)); // surround title with a link
      }
    };
  });

Thank you !

Upvotes: 0

Views: 169

Answers (1)

user1111
user1111

Reputation: 2030

Directive,

.directive('myDirective', function () {
    return {
        restrict: 'A',
        scope:{
            link:'=link',
            title:'=title'
        },
        template:'<a href={{link}}>{{title}}</a>'
    };
});

HTML,

<table>
  <tr ng-repeat='item in items'>
    <td my-directive link='item.link' title='item.title'></td>
    <td my-directive link='item.link' title='item.field'></td>
  </tr>
</table>

Upvotes: 1

Related Questions