URL replace directive
by bmleite
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular-sanitize.js"></script>
<div ng-controller="Ctrl">
<input type="text" ng-model="text">
<p parse-url="props" ng-model="text"></p>
<p ng-bind-html="text | parseUrlFilter:'_blank':'otherProperty'"></p>
</div>
CSS
p {
padding-top: 10px;
}
input {
width: 500px;
}
JavaScript
var app = angular.module('app', ['ngSanitize']);
app.directive('parseUrl', function () {
var urlPattern = /(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/gi;
return {
restrict: 'A',
require: 'ngModel',
replace: true,
scope: {
props: '=parseUrl',
ngModel: '=ngModel'
},
link: function compile(scope, element, attrs, controller) {
scope.$watch('ngModel', function (value) {
var html = value.replace(urlPattern, '<a target="' + scope.props.target + '" href="$&">$&</a>') + " | " + scope.props.otherProp;
element.html(html);
});
}
};
});
app.filter('parseUrlFilter', function () {
var urlPattern = /(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/gi;
return function (text, target, otherProp) {
return text.replace(urlPattern, '<a target="' + target + '" href="$&">$&</a>') + " | " + otherProp;
};
});
function Ctrl($scope) {
$scope.text = 'Example text http://example.com http://example.com http://google.com';
$scope.props = {
target: '_blank',
otherProp: 'otherProperty'
};
}