1

What is the best way to escape HTML in the input field? For example, I've search input field

<input id="search" type="text" ng-model="search" placeholder="search...">

And I want to escape if somebody types something like this:

<script>alert("test123");</script>
lin
  • 17,956
  • 4
  • 59
  • 83
Edin Puzic
  • 998
  • 2
  • 19
  • 39
  • @Fran the question is clear. He wants to escape HTML characters. – lin Dec 06 '17 at 09:32
  • 1
    @lin This Question does not show research effort and the requirements are not clear **to me** when OP wants to escape the characters. Hence I'm asking for more information. – Nope Dec 06 '17 at 09:33

3 Answers3

3

this completely depends on your use case. If you just want it to escape it for the users view (so basically sanitizing) you can use angular $sanitize & $sce for it

https://docs.angularjs.org/api/ngSanitize/service/$sanitize and https://docs.angularjs.org/api/ng/service/$sce

however if you want to store it somewhere and want it escaped, you can build a filter. You can find an example here: Escape HTML text in an AngularJS directive

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Nicolas Gehlert
  • 2,626
  • 18
  • 39
1

You could use lodash _.escape([string='']). This is a easy and simple solution.

_.escape($scope.search);
lin
  • 17,956
  • 4
  • 59
  • 83
-1

You could use pattern for your input box like -

<input type='text' pattern='[a-zA-Z0-9]+'>

Use an expression that best suits your needs.

dbigpot
  • 410
  • 4
  • 11