2

I have an input box and what ever is sent is displayed below using angular.js but if the input is a http url i am trying to convert it to a link. I referred to How to replace plain URLs with links? this SO page..
I am able to convert it to the tag but its not a link. Its just like any other text..

Fiddle link :http://jsfiddle.net/JY3Za/1/

The HTML code :

<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>

and the JS code..

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>"); 
};
};

}

PS: I didnt write the regular expression and it was taken from the above Stackoverflow link for testing..

Community
  • 1
  • 1
Srinath Mandava
  • 3,384
  • 2
  • 24
  • 37
  • Here's a similar issue: [This might help][1] [1]: http://stackoverflow.com/questions/18690804/insert-and-parse-html-into-view-using-angularjs – Tanel Eero Jun 02 '14 at 13:13

1 Answers1

3

If you bind to a value with HTML in it, you should use ngBindHtml, as documented here. The regular bindings (in the form of <span>{{ foo }}</span>) prevent injecting actual HTML for security reasons.

If you use a recent-enough version of AngularJS, also keep in mind the restrictions of $sce documented here, that will require a little bit of extra work to tell AngularJS that the string is safe.

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

As a sidenote, your replaceURLWithHTMLLinks can be made redundant with AngularJS's linky filter, available in the ngSanitize module:

<h1 data-ng-bind-html="yourBindingHere | linky"></h1>
Steve Klösters
  • 9,427
  • 2
  • 42
  • 53