简体   繁体   中英

Formating JSON object output in AngularJS

I have AngularJS web app, which is capable of sending different http methods to our Restful WS. Each request has a preview, where all of it's properties are listed and can be changed in place. Everything works fine except the formating for inputing JSON. It looks like this:

在此处输入图片说明

And I would like it to look like this, except that JSON text was displayed like in picture 1:

在此处输入图片说明

Shortly, I need that the left side was as in 1 pic, and the right side - as in the second pic.

Here's piece of code, which is responsible for generating input for JSON:

<div ng-show="field.restResourceName != null">
    <p ng-show={{field.isRequired}}>{{field.name}}*: </p>
    <p ng-show={{!field.isRequired}}>{{field.name}}: </p>
    <accordion id="entityField" close-others="oneAtATime">
        <accordion-group heading={{field.name}} is-open="false">
            <p>JSON:</p>
            <textarea ng-change="getCreateEntityAsText()" ng-model="createEntityResource[field.name]"></textarea>
        </accordion-group>
    </accordion>
</div>

And here's the one, responsible for showing the output:

<div class="preview">
    <p>Preview: </p>
    <textarea class="form-control" ng-model="createEntityTextAreaModel"></textarea>
</div>

AngularJS controller functions, which parse JSON into model and vice versa:

//CREATE ENTITY JSON PARSE


$scope.getCreateEntityAsText = function () {
    $scope.createEntityTextAreaModel = JSON.stringify($scope.createEntityResource, null, "    ");
};

$scope.$watch('createEntityTextAreaModel', function () {
    applyParseValues($scope.createEntityTextAreaModel, $scope.createEntityResource);
});

applyParseValues = function(textAreaModel, entityModel){
    if($rootScope.isNotEmptyString(textAreaModel)) {
       angular.copy(JSON.parse(textAreaModel), entityModel);
    } else {
        angular.copy({}, entityModel);
    }
}

Any ideas how this can be achieved? Every useful answer is highly appreciated and evaluated.

Thank you.

It looks like you're mostly having a styling issue, which is addressed in this question:

JSON formatter lib

Otherwise, Angular comes with a built-in filter for JSON , which can be used in a view like this:

<p>{{someObject | json }}</p>

Links:

https://docs.angularjs.org/api/ng/filter/json https://docs.angularjs.org/api/ng/filter/json

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM