我希望能够在 <textarea>
中编辑和显示复杂模型元素。这是用于从 JSON 响应动态生成模型字段的 HTML 片段:
<p>parent uuid*: </p>
<input ng-model="parentUuid" capitalize type="text" placeholder="String"
class="form-control" style="width:200px; display: inline-block;"/> <br/>
<p>resource*:</p>
<select ng-model="childResource" ng-change="loadResourceFields(childResource)"
class="form-control" style="width:300px; display: inline-block;">
<option ng-repeat="childResource in restResources">{{childResource}}</option>
</select>
<div ng-repeat="field in childFields">
<div ng-show={{!field.isEnum}}>
<p ng-show={{field.isRequired}}>{{field.name}}*: </p>
<p ng-show={{!field.isRequired}}>{{field.name}}: </p>
<input type="text" ng-model="createChildResource[field.name]"
class="form-control" style="width:200px; display: inline-block;" placeholder="{{parseClassName(field.type)}}">
</div>
<div ng-show={{field.isEnum}}>
<p ng-show={{field.isRequired}}>{{field.name}}*: </p>
<p ng-show={{!field.isRequired}}>{{field.name}}: </p>
<select ng-model="createChildResource[field.name]" class="form-control" style="width:auto; display: inline-block;">
<option></option>
<option ng-repeat="enumValue in field.enumValues" label={{enumValue.name}}>{{enumValue.ordinal}}</option>
</select>
</div>
</div>
<div class="preview">
<p>Preview: </p>
<textarea style="height:350px; width:550px; overflow:scroll;">{{createChildResource | json}}</textarea >
</div>
输出如下:
但是如果我尝试添加 ngModel
到 textarea 元素,以便能够像这样就地编辑此值:
<div class="preview">
<p>Preview: </p>
<textarea ng-model="createChildResource" style="height:350px; width:550px; overflow:scroll;">{{createChildResource | json}}</textarea>
</div>
然后输出如下:
在这两种情况下,我都无法在文本区域元素中编辑我的模型。
如何实现?我希望能够像在 this example 中那样就地显示和编辑我的模型略有不同:editable-textarea="user.description"
应该是 editable-textarea="user"
.
最佳答案
我终于明白你要达到什么目的了。在左侧,您有一堆输入,在右侧(底部),您有一个文本区域,它将输入排列为一个对象的属性,并将它们显示为一个对象的格式。
您的要求是允许用户编辑文本区域中的属性值,从而更新输入中的相应属性值。
首先,如评论所述,将对象转换为字符串,然后将其显示在文本区域内。
接下来,由于您需要在文本区域更新时使用react并更新输入字段,因此您需要观察
文本区域的值并更新原始对象(已转换为字符串的对象) ).
由于您的代码太复杂而难以理解,因此在此使用示例,假设您有对象 containerObject
如下:
$scope.containerObject = {
property_1: "Hello",
property_2: "World"
};
然后您的输入将使用这些属性:
<input ng-model="containerObject.property_1">
<input ng-model="containerObject.property_2">
现在,您希望在文本区域内显示它 - 您首先要将对象转换为字符串并按如下方式显示:
$scope.getObjectAsText = function () {
$scope.textAreaModel = JSON.stringify($scope.containerObject);
};
您的文本区域标记将如下所示:
<textarea ng-model="textAreaModel"></textarea>
每次输入文本框中的值发生变化时,文本区域也会更新。
现在,反过来说。当您更改文本区域时,要更新输入文本框,您需要观察字符串模型(而不是对象模型):
$scope.$watch('textAreaModel', function () {
try {
$scope.containerObject = JSON.parse($scope.textAreaModel);
} catch(exp) {
//Exception handler
};
});
您需要有 try...catch
异常处理程序 block ,因为用户可能会意外更改内容,从而在转换回对象时,结果不是合适的对象(无效的属性或语法无效)。
只要更改属性值,输入值就会正确更新。
关于javascript - Angular JS在textarea中显示和编辑模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22783268/