Luiz Rossi Luiz Rossi - 4 days ago 5
AngularJS Question

Get printed value in ng-bind-html

I need to get text, like is formatted on the

ng-bind-html
, 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"
});


http://jsfiddle.net/r565nb2p/3/

I appreciate you attention reading this. Thank you

Answer

I have made an example on CodePen.io 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.

Comments