angularjs:动态HTML依赖JSON数据 [英] angularjs: dynamic html dependent on json data

查看:213
本文介绍了angularjs:动态HTML依赖JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想告诉我的JSON模型的内容以动态的方式,这取决于所提供的JSON。我使用 NG-重复通过我的数据循环,并要显示一个HTML模板,以填补依赖于遇到的数据类型的数据。

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"
        }
    ]
}

这应导致不同的HTML code,适合充满json的内容。

This should result in different html code, appropriate filled with the json content.

例如

<div><label>Full Name</label> <input type="text"></div>
<div><input type="checkbox"> <label>Accept Terms</label></div>

现在我要做的就是使用一个angularjs指令来创建一个元素和JSON值添加到正确的位置。 例如。 element.html('&LT; D​​IV&GT;&LT;输入类型=复选框&GT;&LT;标签&gt;+ scope.item.desc +'&LT; /标签&gt;&LT; / DIV&GT;')这似乎是jQuery的方式(或更糟)做到这一点,虽然我想这样做正确的方式angularjs。

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.

我如何使用填充内容不同的HTML模板,依赖于遇到的JSON数据?

How can I use a different HTML template filled with content, dependent on the encountered JSON data?

PS:上面的例子是一个简单的,遇到的数据比切换标签输入<位置/复杂得多code>字段中。

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.

推荐答案

一个简单的解决方案似乎使用的 ngSwitch 不同的HTML的路径,例如:

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>

好像使用angularjs指令(这是我第一次了),这种方法可能是复杂的场景为伊晃范,在他的博客文章指出,一个好的解决方案:的 http://onehungrymind.com/angularjs-dynamic-templates/ (感谢!)

这篇关于angularjs:动态HTML依赖JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆