The situation:
I have a small angularjs app that will let me save an "article" and then display it. An article will contain plain text as well as examples of html, js, css, or php code. I can save it no problem using a Laravel 4 backend with MySQL. The trouble comes when I try to display an article. I want to have the code syntax highlighted, so I use the angular-highlight plugin. This makes things a little tricky, but essentially, I put the directive "hljs" around the snippets of code. Then I put a directive around the container tag where the article will go that will $watch
for changes and $compile
the result. That seems to work fine, as the syntax highlighting kicks in. My problem is that angular still does something to my code. It takes <?php
and changes it to <!--?
. It takes <
and changes it to <
. But it leaves html tags like <p>
alone. It is more than a bit infuriating.
The html:
<div dynamic ng-bind-html="article.body"></div>
The directive:
.directive('dynamic', function ($compile, $parse) {
return {
restrict: 'A',
replace: true,
link: function (scope, ele, attrs) {
var parsed = $parse(attrs.ngBindHtml);
function getStringValue() { return (parsed(scope) || '').toString(); }
scope.$watch(function(scope) {
return (parsed(scope) || '').toString();
}, function(html) {
$compile(ele, null, -9999)(scope);
});
}
};
})
What I've done:
I disabled $sce
. Before you tell me that is a bad idea, I am not worried about malicious code. This app will only ever be used by four people and it is inside my network and not accessible from outside it. I disabled $sce
because I thought that is what was changing my code and so I wouldn't have to bother with trustAsHtml()
. I thought the problem might be the highlightjs, but when I remove that, the problem persists. I double and triple check that the content is correct in the database and when it gets requested via $http.get
.
I tried changing the article.body using javascript's .replace()
function, but since angular is $watch
-ing, the code just gets recompiled after my replace, and it goes back to messed up.
EDIT:
article.body
might contain something like this:
<p>Here is an example in PHP:</p>
<div hljs>
<?php
echo "Hello, world!";
?>
</div>