Javascript 将URL从输入转换为链接

Javascript 将URL从输入转换为链接,javascript,html,angularjs,Javascript,Html,Angularjs,我有一个输入框,下面使用angular.js显示发送的内容,但如果输入是http url,我会尝试将其转换为链接。我参考了本SO页面。 我可以将其转换为标签,但它不是链接。它就像其他任何文本一样 小提琴链接: HTML代码: <div ng-app> <div ng-controller="URL"> <form ng-submit="addTodo()"> <input type="text" ng-model="save" siz

我有一个输入框,下面使用angular.js显示发送的内容,但如果输入是http url,我会尝试将其转换为链接。我参考了本SO页面。
我可以将其转换为标签,但它不是链接。它就像其他任何文本一样

小提琴链接:

HTML代码:

<div ng-app>

<div ng-controller="URL">
  <form ng-submit="addTodo()">
      <input type="text" ng-model="save"  size="30"
      placeholder="enter a url"/>
      <input class="btn-primary" type="submit" value="add"/>
</form>
  <h1>{{replaceURLWithHTMLLinks(show)}}</h1>
</div>
</div>

{{replaceurlwithhtmlinks(show)}
还有JS代码

function URL($scope) {
$scope.shoe="";

$scope.addTodo = function() {
$scope.show=$scope.save;
  $scope.replaceURLWithHTMLLinks=function(text) {

var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i;
return text.replace(exp,"<a href='$1'>$1</a>"); 
};
};

}
函数URL($scope){
$scope.shoe=“”;
$scope.addTodo=函数(){
$scope.show=$scope.save;
$scope.replaceurlwithhtmlinks=函数(文本){
var exp=/(\b(https?| ftp | file):\/\/[-A-Z0-9+&@#\/%?=~~|!:,.;]*[-A-Z0-9+&@#\/%=~|]/i;
返回文本。替换(exp,“”);
};
};
}

PS:我没有编写正则表达式,它是从上面的Stackoverflow链接获取的,用于测试。

如果您绑定到一个包含HTML的值,您应该使用
ngBindHtml
,如文档所述。出于安全原因,常规绑定(以
{{foo}}
的形式)阻止注入实际的HTML

如果您使用的是AngularJS的最新版本,还请记住
$sce
中的限制,这将需要一些额外的工作来告诉AngularJS字符串是安全的

<h1 data-ng-bind-html="yourBindingHere"></h1>

这里有一个类似的问题:[这可能会有帮助][1][1]:
<h1 data-ng-bind-html="yourBindingHere | linky"></h1>