AngularJS: JSON 개체에 텍스트 영역 바인딩이 "object-object"를 표시합니다.
Angular는 처음입니다.JS.
개체를 텍스트 영역에 바인딩하려고 합니다.
HTML:
<textarea rows="5" cols="10" ng-model="menuItem.preset"></textarea>
모델:
{
"kind": "title",
"label": "ADD_TITLE",
"iconSrc": "textTitle.png",
"experimentInclude": "",
"experimentExclude": "three",
"preset": {
"compType": "richTitle",
"styleId": "txtNew"
}
}
결과:
JSON 문자열화(나중에 다시 개체로 저장)를 표시하려면 어떻게 해야 합니까?
오브젝트에 대한 입력을 해석하고 오브젝트를 각각 문자열로 표시하는 커스텀 디렉티브가 필요합니다.
예를 들어 다음과 같습니다.
angular.module('yourApp').directive('jsonText', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
function into(input) {
return JSON.parse(input);
}
function out(data) {
return JSON.stringify(data);
}
ngModel.$parsers.push(into);
ngModel.$formatters.push(out);
}
};
});
<textarea json-text rows="5" cols="10" ng-model="menuItem.preset"></textarea>
바이올린: http://jsfiddle.net/HzYQn/
https://github.com/vorburger/MUI.js에 필요했기 때문에, 이것을 「적절한」방법에 대해 조사했습니다.여기 제 솔루션을 가진 Plonker가 있습니다.이는 본질적으로 특수한 경우(즉, 의 적용)에 기초하고 있으며, 관련 Q angular.js에서 양방향 필터링을 수행하는 방법.모델 업데이트는 텍스트 상자도 변경해야 합니다.그게 바로 $watch / $setViewValue / $render의 역할입니다.
var app = angular.module('app', []);
app.directive('jsonText', function() {
return {
restrict: 'A', // only activate on element attribute
require: 'ngModel', // get a hold of NgModelController
link: function(scope, element, attrs, ngModelCtrl) {
var lastValid;
// push() if faster than unshift(), and avail. in IE8 and earlier (unshift isn't)
ngModelCtrl.$parsers.push(fromUser);
ngModelCtrl.$formatters.push(toUser);
// clear any invalid changes on blur
element.bind('blur', function() {
element.val(toUser(scope.$eval(attrs.ngModel)));
});
// $watch(attrs.ngModel) wouldn't work if this directive created a new scope;
// see https://stackoverflow.com/questions/14693052/watch-ngmodel-from-inside-directive-using-isolate-scope how to do it then
scope.$watch(attrs.ngModel, function(newValue, oldValue) {
lastValid = lastValid || newValue;
if (newValue != oldValue) {
ngModelCtrl.$setViewValue(toUser(newValue));
// TODO avoid this causing the focus of the input to be lost..
ngModelCtrl.$render();
}
}, true); // MUST use objectEquality (true) here, for some reason..
function fromUser(text) {
// Beware: trim() is not available in old browsers
if (!text || text.trim() === '') {
return {};
} else {
try {
lastValid = angular.fromJson(text);
ngModelCtrl.$setValidity('invalidJson', true);
} catch (e) {
ngModelCtrl.$setValidity('invalidJson', false);
}
return lastValid;
}
}
function toUser(object) {
// better than JSON.stringify(), because it formats + filters $$hashKey etc.
return angular.toJson(object, true);
}
}
};
});
app.controller('Ctrl', ['$scope',
function($scope) {
$scope.model = {};
$scope.model.data = {
"kind": "title",
"label": "ADD_TITLE",
"iconSrc": "textTitle.png",
"experimentInclude": "",
"experimentExclude": "three",
"preset": {
"compType": "richTitle",
"styleId": "txtNew"
}
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div ng-app="app" class="container">
<div ng-controller="Ctrl" class="row">
<textarea json-text ng-model='model.data' rows="15"></textarea>
<p>{{ model.data }}</p>
</div>
</div>
json 필터로 시도하다
<textarea rows="5" cols="10" >
{{ menuItem.preset | json }}
</textarea>
다음은 유효성 검사를 포함한 JSON 지침입니다.
app.directive('jsonInput', function () {
'use strict';
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, elem, attr, ctrl) {
ctrl.$parsers.unshift(function(input) {
try {
var obj = JSON.parse(input);
ctrl.$setValidity('jsonInput', true);
return obj;
} catch (e) {
ctrl.$setValidity('jsonInput', false);
return null;
}
});
ctrl.$formatters.unshift(function(data) {
if (data == null) {
ctrl.$setValidity('jsonInput', false);
return "";
}
try {
var str = JSON.stringify(data);
ctrl.$setValidity('jsonInput', true);
return str;
} catch (e) {
ctrl.$setValidity('codeme', false);
return "";
}
});
}
};
});
사용자가 비활성 JSON을 입력하면 모델이 null이 됩니다.모델에 순환 참조가 포함되어 있거나 null인 경우 빈 문자열("")이 표시되고 입력이 잘못되었습니다.
즐거운 시간 되세요.
모델에 toString 메서드를 정의할 수도 있습니다.
$scope.menuItem.preset.toString = function(){
return JSON.stringify(this);
}
그리고 백유즈 워치를 동기화합니다.
해결책이라기보다 더러운 해킹에 가깝죠
ng-change 이벤트를 사용하는 것이 너무 지저분한가요?
<textarea ng-model="textmainboardJSON" ng-change="updateMainboard()"
이것은, 다음의 2개의 순서로 실행할 수 있습니다.
- JSON을 문자열화하는 필터를 만듭니다(http://docs.angularjs.org/guide/dev_guide.templates.filters.creating_filters)
$scope.watch
변경 시 저장할 필드(http://jsfiddle.net/ceJ4w/) 참조)
이거 먹어봐.내 경우에는 효과가 있었다.
<textarea rows="5" cols="10" >{{menuItem.preset}}</textarea>
배열 데이터를 angularjs 텍스트 영역에 바인딩하는 간단한 방법이 있습니다.2개의 어레이가 있어 병렬로 표시할 필요가 있는 경우.게다가 jsfiddle에서도 입수할 수 있습니다.
http://jsfiddle.net/Ahsan_Aftab/bc7hd258/18/
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<textarea ng-model="TextAreacodeGroups" style="width:52%;height:200px;" columns="25" id="code_groups">
{{CodeGroupsFun()}}
</textarea>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
var combined;
var array1=['01','02','03','04'];
var array2= ['Students','Teachers','Managers','Operators'];
$scope.CodeGroupsFun = function () {
$scope.TextAreacodeGroups =
combined = array1.map(function (e, i) {
return '\n' + array1[i] + ' - ' + array2[i];
});
};
});
</script>
</body>
</html>
언급URL : https://stackoverflow.com/questions/17893708/angularjs-textarea-bind-to-json-object-shows-object-object
'programing' 카테고리의 다른 글
phpMyAdmin DisplayResults 오류입니다.php #1226 (0) | 2023.03.05 |
---|---|
리액트 컴포넌트의 다른 파일에서 HTML을 렌더링하려면 어떻게 해야 합니까? (0) | 2023.03.05 |
FTP 액세스 없이 Ubuntu 설치 플러그인에서 Word press를 사용합니다. (0) | 2023.03.05 |
브라우저 타임아웃 (0) | 2023.03.05 |
Springboot에 의한 스케줄된 웹 소켓 푸시 (0) | 2023.03.05 |