【发布时间】:2016-07-31 22:02:56
【问题描述】:
我正在尝试在 angularjs 中创建一个 html 视图,用户可以在其中编辑对象属性上的一些值。我在服务中有一个模型对象,然后我还有另一个描述模型对象属性的对象。
描述对象有一个称为参数的对象数组,每个对象都有名称、描述、类型等属性,如下所示:
{
"name": "item",
"description": "An item",
"parameters": [{
"name": "prop1",
"wasNullable": false,
"description": "a property",
"type": "string",
"isRequired": true
}, {
"name": "prop2",
"wasNullable": true,
"description": "a property",
"type": "string",
"isRequired": true
}]
}
我想使用这些数据为要操作的对象构建一个视图。如果属性名称是一个字符串,我想要一个带有文本输入和标签的 html 模板,如下所示:
<label>{{ parameter.name</label>
<input type="text" placeholder="parameter.description"></input>
我希望能够将这些“类型模板”作为单独的 html 文件。
我在如何执行此操作和处理数据绑定方面遇到了麻烦。一种方法是对描述对象上的参数数组执行 ng-repeat,如下所示:
<div ng-repeat="param in $ctrl.definitions.parameters">
<div ng-switch="param.primitiveType">
<div ng-switch-when="string">
<string></string>
</div>
<div ng-switch-when="dateTime">
<date-time></date-time>
</div>
<div ng-switch-when="enum">
<enum></enum>
</div>
</div>
<div ng-if="param.subTypes">
<select ng-model="select.subType">
<option ng-repeat="subType in property.subTypes">{{ subType.name }}</option>
</select>
<div ng-repeat="subType in property.subTypes">
<properties type="subType" ng-if="select.subType === subType.name"></properties>
</div>
</div>
这将解决我的问题,因为我可以为每种类型的属性使用组件,但我不知道如何将数据绑定到服务中存在的另一个对象。
另一种方法是将所有具有默认值的参数从描述对象添加到实际模型对象,然后对引用的模型对象执行 ng-repeat,但我无法使用这种切换到正确 html 的解决方案模板。
关于如何解决这个问题的任何想法?
【问题讨论】:
标签: angularjs templates object dynamic properties