A little over a year ago, I published A Web Page for Reformatting JSON Text, which is a simple web page for pretty-printing JSON data. I'm now learning AngularJS, so as an exercise I reimplemented the page using Angular rather than the original's jQuery.
This version is a little nicer than the original in the following ways:
- You can type or paste text into the top box and the formatted JSON immediately appears in the lower box. There is no longer a need to press a Format button because Angular's data-binding mechanism takes care of automatically updating the output whenever the input changes. (This is possible with jQuery too, but takes more work.)
- You can control the indentation width of the formatted JSON.
- When the input is not valid JSON, the output panel changes its background color to red when displaying the error message.
Here it is: JSON Formatter with AngularJS
Short link: http://bit.ly/formatjson
You can look at the full source here: Gist
or as a fiddle: http://jsfiddle.net/oldmankris/qK9LK/
If don't know anything about AngularJS, but are curious about it, look at the source and note the following:
- The magic of Angular comes from the
ng-attributes attached to HTML elements. There is no need for a separate template language or explicit DOM manipulation. - The ng-app attribute attached to the
htmlelement sets up the module that contains our app's code. - The ng-controller attribute attached to the
divelement defines which controller function to use. - The ng-model attribute attached to the first
textareaelement binds its content to theinputTextvariable - The ng-bind attribute attached to the second
textareaelement binds its content to the value of theoutputTextvariable, and the ng-class attribute binds its CSS class to the value of theoutputClassvariable. - The ng-options and ng-model directives on the
selectelement bind it to theindentOptionsandselectedIndentOptionvariable. - In the controller code, we set initial values for the
inputText,indentOptions, andselectedInputOptionvariables, and then use $scope.$watch() to update the values ofoutputTextandoutputClasswhenever any of the inputs change.