1

How do I parse HTML coming from the server via a string? I have this from the server:

<img src="http://gravatar.com/avatar/9a52267d32ad2aaa4a8c2c45b83396e5?d=mm&amp;s=&amp;r=G" class=" user-1-avatar avatar- photo" width="" height="" alt="Avatar Image" />

which comes in via a object property like:

{admin: {avatar "<img src="http://gravatar.com/avatar/9a52267d32ad2aaa4a8c2c45b83396e5?d=mm&amp;s=&amp;r=G" class=" user-1-avatar avatar- photo" width="" height="" alt="Avatar Image" />"}}

I've tried using ng-bind-html but no luck... What can I use?

2
  • 1
    use $compile service of angularjs. Commented Sep 20, 2014 at 13:28
  • do you have an example? Commented Sep 20, 2014 at 13:30

1 Answer 1

1

later versions of AngularJS:

function HomeCtrl($scope, $sce) {
  $scope.object = {
  admin: {
    avatar : '<img src="http://gravatar.com/avatar/9a52267d32ad2aaa4a8c2c45b83396e5?d=mm&amp;s=&amp;r=G" class=" user-1-avatar avatar- photo" width="" height="" alt="Avatar Image" />'
},
fred: {
    avatar : '<img src="http://gravatar.com/avatar/9a52267d32ad2aaa4a8c2c45b83396e5?d=mm&amp;s=&amp;r=G" class=" user-1-avatar avatar- photo" width="" height="" alt="Avatar Image" />'
}};
  $scope.avatar = $sce.trustAsHtml($scope.object.admin.avatar);
}

HTML:

  <div ng-bind-html="avatar"></div>

Working Demo : http://jsbin.com/butuwu/1/edit

Older version :

HTML:

<div ng-bind-html-unsafe="avatar"></div>

JS:

function HomeCtrl($scope) {
  var object = {
  admin: {
    avatar : '<img src="http://gravatar.com/avatar/9a52267d32ad2aaa4a8c2c45b83396e5?d=mm&amp;s=&amp;r=G" class=" user-1-avatar avatar- photo" width="" height="" alt="Avatar Image" />'
}};
  $scope.avatar = object.admin.avatar;
}
Sign up to request clarification or add additional context in comments.

5 Comments

the problem with this is that it doesn't work when using a modern version of angularJS jsbin.com/rikiyukaloza/1/edit
Updated your jsbin.. check the answer above :)
yeah my problem with that is that it comes in via the server and the value of "admin" is not always the same
In that case, you will be fetching object inside the service.. Then inject it inside the controller.. Just for demo purpose i have stubbed the object inside controller itself.
ended up using: app.filter('unsafe', function($sce) { return function(val) { return $sce.trustAsHtml(val); }; });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.