AngularJs如何调用prettyprint?

Tro*_*sta 3 angularjs

我正在尝试为我的angularjs应用程序使用prettyprint插件.

但不能使它有效.我创建了一个简单的指令和调用方法prettyPrint(),但代码没有格式化.

FIDDLE:http://jsfiddle.net/Tropicalista/yAv4f/2/

App.directive('test', function() {
return {
    restrict: 'A',
    link: function(scope, element, attrs) {
        $(element).prettyPrint()
    }
};
});
Run Code Online (Sandbox Code Playgroud)

Car*_*lla 6

我修改了你的代码,我将在这里更新:http: //jsfiddle.net/yAv4f/6/

HTML:

<div ng-app="Knob" ng-controller="myCtrl">
   <pre class="prettyprint linemus"></pre>
   <pre class="prettyprint linemus">&lt;!DOCTYPE html&gt;&lt;html lang="en"&gt;&lt;/html&gt;</pre>
</div>
Run Code Online (Sandbox Code Playgroud)

JavaScript的:

var App = angular.module('Knob', []);
App.controller('myCtrl', function($scope) {
    $scope.dom = '&lt;!DOCTYPE html&gt;&lt;html lang="en"&gt;&lt;/html&gt;'
})

App.directive('prettyprint', function() {
    return {
        restrict: 'C',
        link: function postLink(scope, element, attrs) {
              element.html(prettyPrintOne(scope.dom));
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

基本上,你需要使用文件prettify.js来控制prettify()函数的执行,使用prettyPrintOne()你可以在特定的html文本中执行它.

为了简化指令的使用,比如美化stlyle,我建议将'C'限制为一个类,并将指令名更改为'prettyprint'


Ken*_*ith 6

我已经扩展了之前的答案并创建了一个带有工作指令的jsfiddle,它可以实时响应模型更改:

http://jsfiddle.net/smithkl42/cwrgLd0L/27/

HTML:

<div ng-app="prettifyTest" ng-controller="myCtrl">
    <div>       
        <input type="text" ng-model="organization.message" />
    </div>
    <prettify target="organization"><pre><code class="prettyprint">console.log('{{target.message}}');
            </code>
        </pre>
    </prettify>
</div>
Run Code Online (Sandbox Code Playgroud)

JS:

var App = angular.module('prettifyTest', []);
App.controller('myCtrl', function ($scope) {
    $scope.organization = {
        message: 'Hello, world!'
    };
});

App.directive('prettify', ['$compile', '$timeout', function ($compile, $timeout) {
    return {
        restrict: 'E',
        scope: {
            target: '='
        },
        link: function (scope, element, attrs) {
            var template = element.html();
            var templateFn = $compile(template);
            var update = function(){
                $timeout(function () {
                    var compiled = templateFn(scope).html();
                    var prettified = prettyPrintOne(compiled);
                    element.html(prettified);
                }, 0);
            }
            scope.$watch('target', function () {
                update();
            }, true);
            update();
        }
    };
}]);
Run Code Online (Sandbox Code Playgroud)

h/t到@DanielSchaffer(参见模板总是用指令中的旧范围值编译).