Code, Angular, iOS and more by Aviv Ben-Yosef

Automatically find links in text using Angular

| Comments

There comes in every web developer’s life a day where he needs to take some block of text and automatically find URLs inside it and transform them into links, inline.

Almost any text that a user inputted would be nicer if it did this automatically.

I don’t know about you, but I’ve accomplished this task in Angular in several ways like jQuery plugins or writing my own regular expressions. It’s not fun adding extra dependencies to accomplish this minor tasks. And it’s always a bit nontrivial to add link support without opening yourself up to some vulnerabilities.

I was quite surprised to hear that there’s a solution to this that comes builtin in Angular and since 1.0: the linky filter.

Setting it up

The linky filter does what you’d expect it to do. Let’s see an example.

First, as the docs say, you need to make sure that you include ngSanitize module file (angular-sanitize.js) and add it as a dependency to your module:

angular.module('myApp', ['ngSanitize']);

The basic usage goes like this:

<div ng-bind-html=" | linky"></div>

This will take and display it regularly, except that URLs inside it, such as would become links. Angular does this safely and sanitizes all the text.

You can quite easily make links open in a new tab or add specific attributes, such as rel=nofollow which is usually recommended when putting up links to user generated content:

<div ng-bind-html=
    " | linky:'_blank':{rel: 'nofollow'}">

And that’s it. Link away!

“Maintaining AngularJS feels like Cobol 🤷…”

You want to do AngularJS the right way.
Yet every blog post you see makes it look like your codebase is obsolete. Components? Lifecycle hooks? Controllers are dead?

It would be great to work on a modern codebase again, but who has weeks for a rewrite?
Well, you can get your app back in shape, without pushing back all your deadlines! Imagine, upgrading smoothly along your regular tasks, no longer deep in legacy.

Subscribe and get my free email course with steps for upgrading your AngularJS app to the latest 1.6 safely and without a rewrite.

Get the modernization email course!