Dynamic Syntax Highlighting with AngularJS and Highlight.js

后端 未结 2 2076
小鲜肉
小鲜肉 2021-02-08 17:43

I am building a site that illustrates common application vulnerabilities such as SQL Injection. I am using AngularJS and highlight.js to creat

2条回答
  •  清酒与你
    2021-02-08 17:59

    In the jsfiddle you have provided you're using angular-highlightjs which in your case basically:

    1. Fetches the template you have provided with include directive applies
    2. Invokes highlightjs library API on the template which produces HTML markup with highlighted elements having correct style for particular language
    3. The highlighted HTML markup is then passed over to angularjs $compile

    Afterwards no highglighting takes place - in particular even when interpolated content changes.

    One way to solve it is to use source directive from angular-highlightjs which is observed but I think it's simpler to build a custom directive.

    The trick here is to manually interpolate and highlight content. I've updated your fiddle with a simplistic highlight directive that presents the idea:

    app.directive('highlight', function($interpolate, $window){
        return {
        restrict: 'EA',
        scope: true,
        compile: function (tElem, tAttrs) {
          var interpolateFn = $interpolate(tElem.html(), true);
          tElem.html(''); // stop automatic intepolation
    
          return function(scope, elem, attrs){
            scope.$watch(interpolateFn, function (value) {
              elem.html(hljs.highlight('sql',value).value);
            });
          }
        }
      };
    });
    

提交回复
热议问题