How to: Opening links in content in system browser instead of Cordova browser wrapper

Hey guys,

I’m not sure if this issue is still bothering anyone, but I wrote a solution today that doesn’t require any code in the controller or a directive. It’s purely using ng-bind-html and a filter that substitutes inline javascript. As far as I can tell this can handle untrusted HTML as well.

See the JSFiddle or the gist:


http://jsfiddle.net/sxcjmoj5/3/

myApp.filter('hrefToJS', function ($sce, $sanitize) {
    return function (text) {
        var regex = /href="([\S]+)"/g;
        var newString = $sanitize(text).replace(regex, "onClick=\"window.open('$1', '_blank', 'location=yes')\"");
        return $sce.trustAsHtml(newString);
    }
});

In your html template:

<div ng-app="myApp">
    <div ng-controller="MyCtrl">
         <h1>Before</h1>

        <p ng-bind-html="html"></p>
        <p ng-bind-html="plaintext"></p>
         <h1>After</h1>

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

Your data bound to the scope:

myApp.controller('MyCtrl', function ($scope) {
    $scope.html = "This a link: <a href='https://www.google.com'>Google</a> :)";
    $scope.plaintext = "This is a link: https://www.google.com :) "
});

You need to include ngSanitize for this, but you can also cut out those sections if you really want to.

11 Likes