angularjs:依赖于 json 数据的动态 html [英] angularjs: dynamic html dependent on json data
问题描述
我想以动态方式显示我的 json 模型的内容,具体取决于提供的 json.我使用 ng-repeat
循环遍历我的数据,并希望显示一个 html 模板以根据遇到的数据类型填充数据.
JSON
<代码>{元素":[{类型":输入文本","desc": "全名"},{"type": "输入复选框","desc": "接受条款"}]}
这应该导致不同的html代码,适当填充json内容.
例如
<input type="text"></div><div><input type="checkbox"><label>接受条款</label></div>现在我要做的是使用 angularjs 指令来创建一个元素并将 json 值添加到正确的位置.<代码>例如element.html('<div><input type="checkbox"> <label>' + scope.item.desc + '</label></div>') 好像喜欢 jquery 方式(或更糟)来做这件事,尽管我想以正确"的 angularjs 方式来做.
如何根据遇到的 JSON 数据使用填充内容的不同 HTML 模板?
PS:上面的例子很简单,遇到的数据远比切换label
和input
字段的位置复杂.
解决方案 一个简单的解决方案似乎使用 ngSwitch 具有不同的 HTML 路径,例如:
<div ng-switch-when="input-text"><div><label>{{item.desc}}</label><input type="text"></div><div ng-switch-when="input-checkbox"><div><input type="checkbox"><label>{{item.desc}}</label></div>
<div ng-switch-default>未知的 item.type: {{item.type}}</div>
Huy Hoang Pham"在他的博客文章中指出,使用 angularjs 指令(我首先采用)的方法似乎是复杂场景的一个很好的解决方案:http://onehungrymind.com/angularjs-dynamic-templates/(谢谢!)
I want to show the content of my json model in a dynamic way, depending on the provided json. I use ng-repeat
to loop through my data and want to display a html template to fill with data dependent on the encountered data type.
JSON
{
"elements": [
{
"type": "input-text",
"desc": "Full Name"
},
{
"type": "input-checkbox",
"desc": "Accept Terms"
}
]
}
This should result in different html code, appropriate filled with the json content.
E.g.
<div><label>Full Name</label> <input type="text"></div>
<div><input type="checkbox"> <label>Accept Terms</label></div>
Right now what I do is to use an angularjs directive to create an element and add the json values to the right spot. e.g. element.html('<div><input type="checkbox"> <label>' + scope.item.desc + '</label></div>')
That seems like the jquery way (or worse) to do it although I want to do it the 'right' angularjs way.
How can I use a different HTML template filled with content, dependent on the encountered JSON data?
PS: The above example is a simple one, the encountered data is far more complex than switching the position of the label
and input
field.
A simple solution seems to use ngSwitch with different HTML paths, e.g.:
<div ng-switch="item.type">
<div ng-switch-when="input-text">
<div><label>{{item.desc}}</label> <input type="text"></div>
</div>
<div ng-switch-when="input-checkbox">
<div><input type="checkbox"> <label>{{item.desc}}</label></div>
</div>
<div ng-switch-default>Unknown item.type: {{item.type}}</div>
</div>
Seems the approach using an angularjs directive (which I took first) may be a good solution for complex scenarios as "Huy Hoang Pham" points out in his blog post: http://onehungrymind.com/angularjs-dynamic-templates/ (thanks!)
这篇关于angularjs:依赖于 json 数据的动态 html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!