Two ways of doing it:
Directive
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);
});
}
};
});
HTML:
<p parse-url="props" ng-model="text"></p>
Filter
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;
};
});
HTML:
<p ng-bind-html-unsafe="text | parseUrlFilter:'_blank':'otherProperty'"></p>
Note: The 'otherProperty'
is just for example, in case you want to pass more properties into the filter.
jsFiddle
Update: Improved replacing algorithm.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…