Use json pretty print in angularjs

Angularjs

Angularjs Problem Overview


How can I use this json pretty print [ http://jsfiddle.net/KJQ9K/ ] with angularJS?

Lets assume myJsonValue is

{a:1, 'b':'foo', c:[false,'false',null, 'null', {d:{e:1.3e5,f:'1.3e5'}}]}

I want to be able to use below to render pre (as shown in example)

Angularjs Solutions


Solution 1 - Angularjs

Angular already has the json filter built-in:

<pre>
  {{data | json}}
</pre>

The json after the pipe | is an Angular Filter. You can make your own custom filter if you like:

app.filter('prettyJSON', function () {
    function prettyPrintJson(json) {
      return JSON ? JSON.stringify(json, null, '  ') : 'your browser doesnt support JSON so cant pretty print';
    }
    return prettyPrintJson;
});

To use your custom prettyJSON filter:

  <pre>
    {{data | prettyJSON}}
  </pre>

ES6 version from @TeChn4K:

app.filter("prettyJSON", () => json => JSON.stringify(json, null, " "))

Solution 2 - Angularjs

Another option is to turn the function into a filter...

app.filter('prettify', function () {
    
    function syntaxHighlight(json) {
        // ...
    }
    
    return syntaxHighlight;
});

HTML...

<pre ng-bind-html="json | prettify"></pre>

JsFiddle: http://jsfiddle.net/KSTe8/

Solution 3 - Angularjs

A simpler code:

app.filter('prettyJSON', function () {
    return function(json) { return angular.toJson(json, true); }
});

Remember to use the <pre> tag

Solution 4 - Angularjs

You have a few options. What I consider the most "AngularJS" way is to wrap your custom object into an Angular service:

myAngularModule.service('myPrettyPrintService', ,myObject );

The inject that into a controller:

myAngularModule.controller('myTestController', function(myPrettyPrintService){}

Then inside the controller, reference the functions and sort:

myPrettyPrintService.syntaxHighlight();

Since anything defined in JavaScript, is global anyway you could technically just access it inside a controller:

syntaxHighlight();

That may screw up with unit testingt because it adds a external, undefined, dependency to your controller.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionaug70coView Question on Stackoverflow
Solution 1 - AngularjsMichael ColeView Answer on Stackoverflow
Solution 2 - AngularjsAnthony ChuView Answer on Stackoverflow
Solution 3 - AngularjschrmcpnView Answer on Stackoverflow
Solution 4 - AngularjsJeffryHouserView Answer on Stackoverflow