Ho creato un filtro AngularJS per creare automaticamente collegamenti selezionabili dagli indirizzi trovati nei dati. Il filtro:Filtro AngularJS che restituisce html come stringa
app.filter('parseUrl', function() {
var //URLs starting with http://, https://, or ftp://
replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim,
//URLs starting with "www." (without // before it, or it'd re-link the ones done above).
replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim,
//Change email addresses to mailto:: links.
replacePattern3 = /(\[email protected][a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;
return function(text, target, otherProp) {
angular.forEach(text.match(replacePattern1), function(url) {
text = text.replace(replacePattern1, "<a href=\"$1\" target=\"_blank\">$1</a>");
});
angular.forEach(text.match(replacePattern2), function(url) {
text = text.replace(replacePattern2, "$1<a href=\"http://$2\" target=\"_blank\">$2</a>");
});
angular.forEach(text.match(replacePattern3), function(url) {
text = text.replace(replacePattern3, "<a href=\"mailto:$1\">$1</a>");
});
return text;
};
});
Ed ecco come sto chiamando (all'interno di un paragrafo):
<p><strong>Details:</strong> {{event.description | parseUrl}}</p>
E questo funziona correttamente per sostituire i collegamenti di testo con il codice per un collegamento. Tuttavia, lo sostituisce con il link letteralmente come testo normale. Ad esempio, www.google.com
verrà sostituito con . Questo chiaramente non rende un link cliccabile, che era il mio obiettivo.
Non sono sicuro del motivo. Qualche idea su come prevenirlo/risolverlo? Grazie.
Si consiglia di dare un'occhiata al filtro "linky" che fornisce AngularJS (http://docs.angularjs.org/api/ngSanitize.filter:linky) nel modulo ngSanitize - quel filtro potrebbe già fare ciò che si necessario, e la documentazione per esso supporta i suggerimenti formulati nelle risposte riguardanti le direttive ng-bind-html/ng-bind-html-non sicure. – CBerube