I have an AngularJS application, which collects data from input, transforms a model into a string using JSON.stringify()
and lets a user edit this model in such a way that input fields get updated if the <textarea>
element is updated and vice versa. Some kind of two-way binding :)
The problem is that the String itself looks ugly and I would like to format it so it looks like this:
And not like it looks now:
Any ideas how this can be accomplished? If you need some additional info - don't hesitate asking. Every answer is highly appreciated and answered immediately.
Thank you.
P.S. I guess this should be some kind of directive or a custom filter. Data itself SHOULD NOT be changed, only the output.
Use JSON. stringify(obj) method to convert JavaScript objects into strings and display it. Use JSON. stringify(obj, replacer, space) method to convert JavaScript objects into strings in pretty format.
The json filter in AngularJs is used to convert a JavaScript object into a JSON. string.
For that, we can use a method JSON. stringify(), which is used to convert the object data into the JSON format. We have created an object data using variable myData, where we have stored the data as an object, and we are going to convert it using JSON.
AngularJS json FilterThe json filter converts a JavaScript object into a JSON string. This filter can be useful when debugging your applications. The JavaScript object can be any kind of JavaScript object.
Angular has a built-in filter
for showing JSON
<pre>{{data | json}}</pre>
Note the use of the pre
-tag to conserve whitespace and linebreaks
Demo:
angular.module('app', []) .controller('Ctrl', ['$scope', function($scope) { $scope.data = { a: 1, b: 2, c: { d: "3" }, }; } ]);
<!DOCTYPE html> <html ng-app="app"> <head> <script data-require="[email protected]" data-semver="1.2.15" src="//code.angularjs.org/1.2.15/angular.js"></script> </head> <body ng-controller="Ctrl"> <pre>{{data | json}}</pre> </body> </html>
There's also an angular.toJson
method, but I haven't played around with that (Docs)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With