0

I am trying to replicate ng-bind-html-unsafe with $sce.trustAsHtml as a filter, as given here

When I try to pass a text such as:

"Code: <?php echo strtotime($user->created_at)*1000; ?>"

it gets rendered as:

"Code: created_at)*1000; ?>"

How do I get the whole text rendered?

UPDATE:

My code is as follows:

HTML:

<p ng-bind-html="message.messagebody | newlines | unsafe"></p>

Filters:

app.filter('newlines', function () {
  return function (text) {
    return text.replace(/\n/g, '<br/>');
  }
})

app.filter('unsafe', ['$sce',
  function ($sce) {
    return function (val) {
      return $sce.trustAsHtml(val);
    }
  }
])

I am using ng-bind-html so that whenever a new line is entered, it is converted into a "<br/>" tag and displayed as a new line when rendered in the browser.

Adi Prasetyo
  • 1,006
  • 1
  • 15
  • 41
Prateek Bhatt
  • 23
  • 1
  • 6
  • 1
    why do you use trustAsHtml? i what happens if you just past the text as is? – Liad Livnat Jul 20 '14 at 13:41
  • **`<`** isn't valid html, try converting to htmlentities or create your own directive to set the html so it isn't being run through `$sce` – charlietfl Jul 20 '14 at 14:26
  • When a user enters a new line character it needed to be converted into
    tag so that the new line is reflected when rendered in the browser. Otherwise it comes in the same line. This is why I have used ng-bind-html instead of ng-bind.
    – Prateek Bhatt Jul 20 '14 at 16:59
  • old q, have you solve it on your own @Prateek Bhatt ? – Adi Prasetyo May 10 '20 at 11:57

1 Answers1

0

Please see this fiddle.

Simply use angular variable in html.

HTML

<div ng-app="app" ng-controller="TestController">
    <h3>Not worked</h13>
    <pre>Code: <?php echo strtotime($user->created_at)*1000; ?></pre>

    <h3>Worked</h3>
    <pre>{{data.html}}</pre>
</div>

JavaScript

var app = angular.module('app', []);
app.controller('TestController', function($scope){
    $scope.data = {};
    $scope.data.html = "Code: <?php echo strtotime($user->created_at)*1000; ?>";
});
SM Adnan
  • 555
  • 2
  • 10
  • this will not work when i use ng-bind-html instead of using angular variable. It will throw an error. – Prateek Bhatt Jul 21 '14 at 10:31
  • The example I posted worked for me. So, do not use ng-bind-html then. – SM Adnan Jul 21 '14 at 17:05
  • I know your example works. However, I need to use ng-bind-html for a different purpose: to convert newlines to break-tags and render them as html. Is there a way to make it work with ng-bind-html ? – Prateek Bhatt Jul 21 '14 at 18:58