Skip to content Skip to sidebar Skip to footer

Angularjs + Highlight.js (to Evaluate String With Expression In Directive)

I am trying to create a highlight.js directive and I am having problems getting scope vars to apply.

Solution 1:

The key is you should use $interpolate instead of $compile

Description of $interpolate

Compiles a string with markup into an interpolation function. This service is used by the HTML $compile service for data binding. See $interpolateProvider for configuring the interpolation markup.

When you use $complie, it will turn your string into element.

Description of $compile

Compiles a piece of HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.

(To be honest, I don't really understand the description until trying it out.)

Here is the working plunk

app.controller('MainCtrl', function($scope) {
  $scope.cdnPath = "//path/to/cdn/";
  $scope.version = "1.0"; 
});

app.directive('snippet', ['$timeout', '$interpolate', function($timeout, $interpolate) {
    return {
        restrict: 'E',
        template:'<pre><code ng-transclude></code></pre>',
        replace:true,
        transclude:true,
        link:function(scope, elm, attrs){             
            var tmp =  $interpolate(elm.find('code').text())(scope);
             $timeout(function() {                
                elm.find('code').html(hljs.highlightAuto(tmp).value);
              }, 0);
        }
    };
}]);

Solution 2:

You'll need to $compile the inner HTML. See the fiddle below. You also don't need to run w/in an $apply block.

app.directive('snippet', ['$timeout', '$compile', function($timeout, $compile) {
    var template = '<pre><code></code></pre>';

    return {
        restrict: 'E',
        compile: function(tElement, tAttrs, transclude) {

            var rawCode = tElement.text();
            tElement.html(template);

            returnfunction(scope, element, attrs) {

                var g = $compile(rawCode)(scope);

                $timeout(function() {
                    var text = g[0].outerHTML;
                        var formattedCode = hljs.highlightAuto(text);
                        $(element).find('code').html(formattedCode.value);
                }, 0);
            }
        }
    }
    }]);​

http://jsfiddle.net/roytruelove/jMC9n/1/

Post a Comment for "Angularjs + Highlight.js (to Evaluate String With Expression In Directive)"