Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

javascript - AngularJS format JSON string output

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:

enter image description here

And not like it looks now:

enter image description here

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...