URL replace directive

by bmleite

HTML

<div ng-controller="Ctrl">
    <input type="text" ng-model="text">
        
    <p parse-url="props" ng-model="text"></p>
    <p ng-bind-html-unsafe="text | parseUrlFilter:'_blank':'otherProperty'"></p>  
        
</div>

CSS

p {
    padding-top: 10px;
}
input {
    width: 500px;
}

JavaScript

var app = angular.module('app', []);

app.directive('parseUrl', function() {
  var urlPattern = /(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&amp;:\/~+#-]*[\w@?^=%&amp;\/~+#-])?/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) {         
            angular.forEach(value.match(urlPattern), function(url) {
                value = value.replace(url, "<a target=\"" + scope.props.target + "\" href="+ url + ">" + url +"</a>");
            });
            element.html(value + " | " + scope.props.otherProp);        
          });                
    }
  };  
});

app.filter('parseUrlFilter', function() {
    var urlPattern = /(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&amp;:\/~+#-]*[\w@?^=%&amp;\/~+#-])?/gi;
    return function(text, target, otherProp) {        
        angular.forEach(text.match(urlPattern), function(url) {
            text = text.replace(url, "<a target=\"" + target + "\" href="+ url + ">" + url +"</a>");
        });
        return text + " | " + otherProp;        
    };
});


function Ctrl($scope) {
    $scope.text = 'Example text http://example.com http://google.com';  
    $scope.props = {        
        target: '_blank',
        otherProp: 'otherProperty'
    };
}