1+ angular . module ( 'JSONFormaterApp' , [ ] )
2+
3+ . controller ( 'JSONFormaterController' , [ '$scope' , '$window' , function ( $scope , $window ) {
4+ $scope . inputText = '' ;
5+ // List of All indentations
6+ $scope . indentOptions = [
7+ { label : 'None' , value : 0 } ,
8+ { label : 'One Space' , value : 1 } ,
9+ { label : 'Two Spaces' , value : 2 } ,
10+ { label : 'Three Spaces' , value : 3 } ,
11+ { label : 'Four Spaces' , value : 4 }
12+ ] ;
13+ //Default Indentation
14+ $scope . selectedIndentOption = $scope . indentOptions [ 2 ] ;
15+ // Clear Input
16+ $scope . clearInput = function ( ) {
17+ $scope . inputText = '' ;
18+ $window . document . getElementById ( 'inputTextarea' ) . focus ( ) ;
19+ } ;
20+ $scope . $watch ( 'inputText' , formattedOutput ) ;
21+ $scope . $watch ( 'selectedIndentOption' , formattedOutput ) ;
22+ //Output according User's Point
23+ function formattedOutput ( ) {
24+ try {
25+ var indent = $scope . selectedIndentOption . value ;
26+ $scope . indent = indent ;
27+ $scope . outputText = updatedJSON ( $scope . inputText , indent ) ;
28+ $scope . outputClass = 'text-success' ;
29+ }
30+ catch ( err ) {
31+ $scope . outputText = err . message ;
32+ $scope . outputClass = 'text-danger' ;
33+ }
34+ }
35+
36+ function updatedJSON ( input , indent ) {
37+ if ( input . length == 0 ) {
38+ return '' ;
39+ }
40+ else {
41+ var parsedData = JSON . parse ( input ) ;
42+ $scope . indent = indent ;
43+ return JSON . stringify ( parsedData , null , indent ) ;
44+ }
45+ }
46+
47+ $scope . copyToClipboard = function ( ) {
48+ var copyFrom = document . createElement ( "textarea" ) ;
49+ copyFrom . textContent = $scope . outputText ;
50+ var body = document . getElementsByTagName ( 'body' ) [ 0 ] ;
51+ body . appendChild ( copyFrom ) ;
52+ copyFrom . select ( ) ;
53+ document . execCommand ( 'copy' ) ;
54+ body . removeChild ( copyFrom ) ;
55+ }
56+
57+ $scope . downloadJSON = function ( ) {
58+ var blob = new Blob ( [ updatedJSON ( $scope . inputText , $scope . indent ) ] , { type : "application/json;charset=utf-8;" } ) ;
59+ var downloadLink = angular . element ( '<a></a>' ) ;
60+ downloadLink . attr ( 'href' , window . URL . createObjectURL ( blob ) ) ;
61+ const date = new Date ( ) ;
62+ const formattedDate = date . toLocaleString ( 'en-GB' , {
63+ day : 'numeric' , month : 'short' , year : 'numeric' , hour : '2-digit' , minute : '2-digit'
64+ } ) . replace ( / / g, '-' ) ;
65+ downloadLink . attr ( 'download' , formattedDate + '.json' ) ;
66+ downloadLink [ 0 ] . click ( ) ;
67+ }
68+
69+ } ] ) ;
0 commit comments