AngularJS 형식 JSON 문자열 출력
입력에서 데이터를 수집 JSON.stringify()
하고 사용 하여 모델을 문자열로 변환하는 AngularJS 애플리케이션 이 있으며 <textarea>
요소가 업데이트 되면 입력 필드 가 업데이트되고 그 반대의 경우도 마찬가지입니다. 어떤 종류의 양방향 바인딩 :)
문제는 문자열 자체가보기 흉해서 다음과 같이 형식화하고 싶다는 것입니다.
그리고 지금처럼 보이지 않습니다.
이것이 어떻게 달성 될 수 있는지 어떤 아이디어? 추가 정보가 필요하면 주저하지 말고 물어보세요. 모든 답변은 높이 평가되고 즉시 답변됩니다.
감사합니다.
추신 나는 이것이 일종의 지시문이나 사용자 지정 필터 여야한다고 생각합니다. 데이터 자체는 변경되지 않아야하며 출력 만 변경되어야합니다.
다음의 선택적 매개 변수를 사용할 수 있습니다. JSON.stringify()
JSON.stringify(value[, replacer [, space]])
매개 변수
- value JSON 문자열로 변환 할 값입니다.
- replacer If a function, transforms values and properties encountered while stringifying; if an array, specifies the set of properties included in objects in the final string. A detailed description of the replacer function is provided in the javaScript guide article Using native JSON.
- space Causes the resulting string to be pretty-printed.
For example:
JSON.stringify({a:1,b:2,c:{d:3, e:4}},null," ")
will give you following result:
"{
"a": 1,
"b": 2,
"c": {
"d": 3,
"e": 4
}
}"
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="angular.js@1.2.15" 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 are looking to render JSON as HTML and it can be collapsed/opened, you can use this directive that I just made to render it nicely:
https://github.com/mohsen1/json-formatter/
이미 언급 한 각도 json
필터 외에도 각도 toJson()
함수가 있습니다.
angular.toJson(obj, pretty);
이 함수의 두 번째 매개 변수를 사용하면 예쁜 인쇄를 켜고 사용할 공백 수를 설정할 수 있습니다.
true로 설정하면 JSON 출력에 줄 바꿈과 공백이 포함됩니다. 정수로 설정하면 JSON 출력에 들여 쓰기 당 많은 공백이 포함됩니다.
(기본값 : 2)
json 텍스트를 편집하는 데 사용하고 싶은 것 같습니다. 그런 다음 ivarni의 방식을 사용할 수 있습니다.
{{데이터 | json}}adition 속성을 추가하여
편집 가능
<pre contenteditable="true">{{data | json}}</pre>
이것이 당신을 도울 수 있기를 바랍니다.
JSON 형식을 지정하고 구문 강조를 수행하려면 ng-prettyjson
지시문을 사용할 수 있습니다 . npm 패키지를 참조하십시오.
사용 방법은 다음과 같습니다. <pre pretty-json="jsonObject"></pre>
참고 URL : https://stackoverflow.com/questions/22785552/angularjs-format-json-string-output
'program story' 카테고리의 다른 글
ASP.NET에서 루트 도메인 URI를 얻으려면 어떻게해야합니까? (0) | 2020.09.04 |
---|---|
Git에 동시에 여러 파일을 추가하는 방법 (0) | 2020.09.04 |
카운터에 변수 "i"및 "j"가 사용되는 이유는 무엇입니까? (0) | 2020.09.04 |
파일을 특정 개정으로 재설정하거나 되돌리려면 어떻게합니까? (0) | 2020.09.04 |
Robolectric으로 ViewPager (및 CursorLoader) 테스트 (0) | 2020.09.04 |