Clean way to copy element text to title attribute using AngularJS
The table has something like this:
<tr ng-repeat="book in books">
<td title="{{book.title}}">{{book.title}}</td>
<td title="{{book.author}}">{{book.author}}</td>
</tr>
I am using CSS to display ellipses on overflow, and I would like a tooltip to show on hover that shows the full intended content of the cell, thus using the title attribute. In the example above, it isn't that bad, but other times I have more complex AngularJS expressions with filters and the like, and I hate repeating the same thing in both the content and the title attribute.
Is it possible to use some AngularJS magic (maybe?) To automatically copy the content of the generated element into the title attribute (or vice versa), and if so, how to do it?
Sorry if this is a newbie question, but I'm new to AngularJS and my Google attempts to find a solution turned out to be short.
source to share
You can write a very simple directive that will just get the inner content and set it as a header:
app.directive('contentTitle', function($timeout) {
return {
link: function(scope, element) {
$timeout(function() {
element[0].title = element[0].textContent;
});
}
};
});
and use it like this:
<tr ng-repeat="book in books">
<td content-title>{{book.title}}</td>
<td content-title>{{book.author}}</td>
</tr>
Note 1: I wrapped the code in $timeout
to make sure it runs after the element's content is correctly interpolated.
Note 2: If you support IE8 then you should use innerText for this, then cross-browser way will be element[0].textContent || element[0].innerText
.
Demo: http://plnkr.co/edit/rXgHwaeScsQdYlFMC7yR?p=preview
source to share