Reputation: 4581
I am trying to manipulate the html of a table to replace all text in cells that have links with a <a>
link that is clickable using AngularJS.
When the DOM is loaded I have the following code:
...
$("td").each(function (index) {
if($(this).text())
{
$(this).text($ctrl.linkify($(this).text().toString()));
}
});
...
$ctrl.linkify = function(text) {
var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
return text.replace(urlRegex, function (url) {
return '<a href="' + url + '">' + url + '</a>';
});
}
However it doesn't render the links as clickable link elements.
An important note is that the table is added dynamically by a third party plugin so I can only manipulate it after it has loaded. Hence why in the title I mentioned after the table has been rendered.
How can I use angular js to linkify the cells? Or use sanitize to render the new html?
Upvotes: 1
Views: 316
Reputation: 1668
You are seeing it as text because ng-model or {{}} shows only text, you need to show them as html and in this case you can use ngBingHtml directive. To use it, you must include into your project angular-sanitize and after it in your table you can use in this way:
Here a working example
var editor = angular.module("editor",['ngSanitize']);
var app = angular.module('plunker', ['editor']);
editor.controller('EditorController', function($scope) {
$scope.values = ['Normal text',
'https://www.google.com/',
'This is not a link'];
$scope.replaceUrlWithATag = function(text){
var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
return text.replace(urlRegex, (url) => {return '<a href="' + url + '">' + url + '</a>'});
}
});
editor.directive("editorView",function(){
return {
restrict :"EAC",
templateUrl : "editor.html",
scope : {
content : "=editorView"
},
link : function(scope,element,attrs){
}
};
});
app.controller('BaseController', function($scope) {
$scope.content = 'World';});
<!doctype html>
<html ng-app="plunker" >
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
<link rel="stylesheet" href="style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular-sanitize.min.js"></script>
</head>
<body>
<div ng-controller="EditorController">
<table class="table table-bordered">
<tr>
<th>ID</th>
<th>Value</th>
</tr>
<tr ng-repeat="v in values">
<td>{{$index}}</td>
<td ng-bind-html="replaceUrlWithATag(v)"></td>
</tr>
</table>
</div>
</body>
</html>
Upvotes: 1