Render Html with Scope Variable

122 views
Skip to first unread message

Rob

unread,
Jan 31, 2015, 11:42:02 PM1/31/15
to ang...@googlegroups.com
I need to render some html code AFTER angularjs has loaded. That html code includes an scope variable value. So in principle I have the following:

$scope.renderHtml = function (htmlCode) { return $sce.trustAsHtml(htmlCode); };
$scope.testText = "hello";
$scope.testing = '<h1>{{testText}}</h1>';
...
<div ng-bind-html="renderHtml(testing)"></div>

The result of this is "{{testText}}" rather than "hello". So it seems it is not possible to render html code that uses the content of a scope variable. Is this correct or am I doing something wrong? Is there another way to achieve the same (render html AFTER angularjs has loaded and that html uses a the content of a scope variable)?



Sander Elias

unread,
Feb 1, 2015, 6:52:35 AM2/1/15
to ang...@googlegroups.com
Hi Rob

There are many ways in angular your problem can be solved. Building HTML by hand, is usually not needed at all. It can be done, but is usually not the best way forward.
I think that in your case a simple template directive is enough for what you want to do. 
If you really need to compile your on HTML into angular you need to look into $compile.

Regards
Sander

Rob

unread,
Feb 3, 2015, 12:26:11 AM2/3/15
to ang...@googlegroups.com
Sander,

I have tried using a directive. However, that failed. For your information, I have a controller that loads data using $q.all and that data is assigned to a scope variable. I then used that variable in the directive with 'element.appned("...." + scope[attrs["myExpression"]] + "...")'. However, the directive is executed before $q.all finished and once $q.all finished and the scope variable is set the directive does not update (I assume it's not assigned to do so). Now I could move all the controller code into the directive and do my $q.all there but I assume that would be bad design.


Sander Elias

unread,
Feb 3, 2015, 1:38:55 AM2/3/15
to ang...@googlegroups.com
Hi Rob,

Yes you are right, that would be bad design indeed. In such a situation, you need to put it in a service, and inject that service in both the controller and the directive,
 
Regards
Sander
Reply all
Reply to author
Forward
0 new messages