Skip to content

Instantly share code, notes, and snippets.

@deyvi-james
Forked from rewonc/app.js
Created February 10, 2016 05:25
Show Gist options
  • Save deyvi-james/3508269bf64c40724428 to your computer and use it in GitHub Desktop.
Save deyvi-james/3508269bf64c40724428 to your computer and use it in GitHub Desktop.
AngularJS/PhoneGap/Ionic: filter to convert links for opening in separate mobile window
//*
//* See the JS Fiddle: http://jsfiddle.net/sxcjmoj5/3/
//*
//*
// make sure ngSanitize module is installed:
// https://docs.angularjs.org/api/ngSanitize
//
// To convert links from plaintext, you must use the linky filter which is included with ngSanitize
// https://docs.angularjs.org/api/ngSanitize/filter/linky
//
// You might need to install inappbrowser if you haven't done that:
// https://github.com/apache/cordova-plugin-inappbrowser/blob/master/doc/index.md
//
// In your app.js
var myApp = angular.module('myApp', ['ngSanitize']);
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);
}
});
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 :) "
});
///Usage 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>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment