One pre
tag on the page contains dynamic text that is unknown during page load. This text may include ng commands, as shown below:
<pre>
Hello <span ng-click="test('args')">world</span> angular-JS!
</pre>
Since these dynamic tags do not exist when the page loads, AngularJS does not run them and the function test('args')
will never execute.
To address this issue, I have implemented a directive called compile-template
:
function compileTemplate($compile, $parse)
{
return {
link: function (scope, element, attr)
{
var parsed = $parse(attr.ngBindHtml);
function getStringValue() { return (parsed(scope) || '').toString(); }
//Recompile if the template changes
scope.$watch(getStringValue, function ()
{
$compile(element, null, -9999)(scope); //The -9999 makes it skip directives so that we do not recompile ourselves
});
}
}
}
Now, my pre
tag looks like this:
<pre compile-template>
Hello <span ng-click="test('args')">world</span> angular-JS!
</pre>
This solution works well.
The problem arises when the text changes to something like this:
<pre compile-template>
Hello <span ng-click="test('args')">world</span> angular-JS! }}
</pre>
When attempting to compile this text ("Hello world angular-JS! }}"), an error occurs:
Error: [$parse:lexerr] http://errors.angularjs.org/1.5.8/$parse/lexerr?p0=Unexpected%20next%20character%20&p1=s%200-0%20%5B%23%5D&p2=%23coordinates%3A21%7C37%7CN%7C87%7C04%7CW%7C%7C%7C%0A%0A%0A%7C%0A%7Cname%3D
at angular.js:38
at jc.throwError (angular.js:14179)
at jc.lex (angular.js:14101)
at s.ast (angular.js:14303)
at td.compile (angular.js:14771)
at kc.parse (angular.js:15700)
at g (angular.js:15865)
at k (angular.js:12364)
at ca (angular.js:9724)
at $b (angular.js:8743)
This error is due to the "}}" string being associated with broken JS code.
For example: https://jsfiddle.net/m69q87eg/
To solve this issue, I aim to allow only <span>
elements with JS functionality, no other HTML content. My thought was to move the compile-template
directive to be part of the span element, like so:
<pre>
Hello <span compile-template ng-click="test('args')">world</span> angular-JS!
</pre>
However, this approach does not work as the outer pre
HTML is treated as plain text.
How can I resolve this issue?