Luiz Rossi Luiz Rossi - 1 year ago 62
AngularJS Question

Get printed value in ng-bind-html

I need to get text, like is formatted on the

, but in an angular variable. Is a little hard to explain textually, see if is comprehensible in this code and fiddle:

var testApp = angular.module('TestApp', []);

testApp.controller('TestController', function($scope, $sce) {
$scope.wrappedValue = $sce.trustAsHtml('asdf<div>&deg;C<br />aaa</div>'); //this is my input
var data = $scope.wrappedValue;
console.log(data); //here I want to get printed: "asdf\n°C\naaa"

I appreciate you attention reading this. Thank you

Answer Source

I have made an example on that shows two different ways to get this text parsed.

First attempt:

var data = 'asdf<div>&deg;C<br />aaa</div>';
var tempDiv = document.createElement('div');
tempDiv.innerHTML = data;
console.log(tempDiv.innerText || tempDiv.textContent);

As you can see in this attempt I use a tempDiv that is never added to the DOM. But, since we set innerHTML to hold the exact value on the data variable, we can call innerText/textContent on it.

First one's result diverges a little on what you want, it does not have a separate line for '°C'.

Second attemp

$timeout(function() {
    var iCanHaveAnId = document.getElementById('iCanHaveAnId');
    console.log(iCanHaveAnId.innerText || iCanHaveAnId.textContent);

This one results on three rows, as you expect. It takes advantage of $timeout to allow Angular to digest everything first and then go to the div#iCanHaveAnId, which is marked with ng-bind-html directive, and get its content.

Hopefully, one of those strategies will help you.

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