Tân Nguyễn Tân Nguyễn - 1 year ago 70
AngularJS Question

How to display custom html tag?

I'm trying to read user input text and display it.

I've tried:

<input type="text" ng-model="post.content" />

<div ng-bind-html="post.content| htmlize"></div>


let app = angular.module('myApp', ['ngSanitize']);

app.controller('myController', function ($scope) {

// controller implements...


{ expr: /\n+?/g, value: '<br />' },
{ expr: /\[([BUI])\](.+)\[\/\1\]/g, value: '<$1>$2</$1>' }

]).filter('htmlize', function (HTMLIZE_CONVERSIONS) {

return function (string) {
return HTMLIZE_CONVERSIONS.reduce(function (result, conversion) {
return result.replace(conversion.expr, conversion.value);
}, string || '');


When I type:

[B]bold[/B] [U]underline[/U] [I]italic[/I]

it would convert to:

bold u̲n̲d̲e̲r̲l̲i̲n̲e̲ italic

My question: how to prevent the code detects other html tags?

I've tried:








My goal: I just only want to convert
and display them as html tags (as I show), ortherwise; display it as an plain text.

How can I do that?

Answer Source

You can

replace < with &lt;

replace > with &gt;

to display < and > in plain text and then replace [ and ] characters with < and > to make them correct HTML tags

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download