Use json pretty print in 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, " "))
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/
A simpler code:
app.filter('prettyJSON', function () {
return function(json) { return angular.toJson(json, true); }
});
Remember to use the <pre>
tag